Chinchan Zu
Chinchan Zu

Reputation: 918

JQuery: Reading the JSON response of the server

OK, I have this piece of code,

var record = new Object(); //var aData = {};でもOK  
record["deviceID"] = "123456"; //aData["name"] = "hoge"でもoK  
$.getJSON("http://192.168.2.10:8080/commapi/comaction/init", {record: JSON.stringify(record)},
function(objRes){  
    alert(objRes["response"]); //objRes["country"]でもok  
}); 

I just made a simple servlet that simply replies back the deviceID I put. But my problem is there is an error like

XMLHttpRequest cannot load http://192.168.2.10:8080/commapi/comaction/init?record=%7B%22deviceID%22%3A%22123456%22%7D. Origin file:// is not allowed by Access-Control-Allow-Origin.

how can I fix this? Thank you!

UPDATED SCRIPT I tried using the JSONP, and my resulting script looks like this

$(document).ready(function() {
  $("#ui-2").click(function(){
      getJSON("http://192.168.2.143:8080/commapi/comaction/init?record=%7B%  22deviceID%22%3A%22123456%22%7D&callback=loaded"); 
  });
};


function getJSON(url){
var s = document.createElement('script');
  s.setAttribute('src',url);
  document.getElementsByTagName('head')[0].appendChild(s);

  // Loading ..
  $("results").innerHTML = '<p>Loading &hellip;</p>'; 
};


function loaded(data) { 

var res = data.query.results.item;
var html = "";
var i =  0;
var y = res.length;

for(i; i<y; i++) { 
    alert(data.deviceID);
} 

};

but this is the new error Resource interpreted as Script but transferred with MIME type application/json.

Upvotes: 0

Views: 516

Answers (2)

Abdul Munim
Abdul Munim

Reputation: 19217

We are not allowed to do Cross-site HTTP requests from JavaScript. That is, you are only allowed to make AJAX requests to your own requestee domain only.

You can only be successful with http://192.168.2.10:8080/commapi/comaction/init AJAX call if the AJAX call is made from the same domain as http://192.168.2.10:8080.

As a workaround, this is often accomplished by JSONP which passes a JavaScript callback function which is a JavaScript function located on your page and requests to the server where the server wraps the JSON data with callback function. This is executed by creating a <script></script> tag with src attribute to be the AJAX url and appended to the HTML body.

PS: You server must have capability to wrap your output data which will require to change on your http://192.168.2.10:8080/commapi/comaction/init codes.

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382909

That is due to Same Origin Policy in other words, host and port should be same.

To work around it, have a look at JSONP.

Here is a resouce to get you started.

Upvotes: 3

Related Questions