0

Consider the following code:

var jsonData1 = $.ajax({

      url: 'http://'+domainName+':9898/jolokia/read/*',
      dataType:"json",
      crossDomain: true,
      beforeSend: function(xhr){
          var username= '*';
          var password= '*';
            xhr.setRequestHeader("Authorization",
                "Basic " + btoa(username + ":" + password));

        },
      async: false
      }).responseText;

  var parsed1 = JSON.parse(jsonData1);

Here when I directly access the url, it asks for a username and password, which when given shows the value. But when I do it through an ajax call, it throws this error:

Failed to load resource: the server responded with a status of 401 (Unauthorized)
jquery.min.js:5 XMLHttpRequest cannot load     http://10.91.240.21:9898/jolokia/read/* No     'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 401.
 (index):1 Uncaught SyntaxError: Unexpected token u

TRY 2:

      var jsonData2 = $.ajax({
        type:'GET',
      url: 'http://'+domainName+':9898/jolokia/read/*',
      dataType:"jsonp",
      crossDomain: true,
      data: {username: '*',password: '*'},
      async: false
      }).responseText;

  var parsed2 = JSON.parse(jsonData2);

I tried using json p. The unauthorized code got resolved. It is showing status OK. But now this error comes

Uncaught SyntaxError: Unexpected token u
11
  • stackoverflow.com/questions/5507234/… Commented Nov 25, 2014 at 4:36
  • @Cheery I am using the beforeSend argument. Commented Nov 25, 2014 at 4:39
  • Look at the second answer by the link. Modern jQuery has attributes for username and password. Or, at least, attribute headers Commented Nov 25, 2014 at 4:41
  • @Cheery That ain't working too. Commented Nov 25, 2014 at 4:42
  • Then press F12 in the browser, check how data is sent. Compare to what your browser is sending directly. Commented Nov 25, 2014 at 4:43

1 Answer 1

1

I think I got the answer. The cross domain issue is resolved.

        $(document).ready(function() {
        var surl = "http://www.anotherdomain.com/webservice.asmx";
        $.ajax({
            type: 'GET',
            url: surl,
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            data: { UserID: 1234 },
            dataType: "jsonp",
            async: false,
            cache: false
         });
         });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.