JQuery obtains the JSON data of the same domain
First, refer to the jQuery library file:
<script src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js">
</script>
jQuery code:
var url="http://localhost:8000/user.php"; $(function() { $.getJSON(url,function(data) { alert (data.name);}) });
Server code (PHP):
<?php header('Content-Type:text/html;Charset=utf-8'); $arr = array( "name" => "xiaoming", "pass" => "123456" ); echo json_encode($arr); ?>
The server returns a string:
{"name":"xiaoming","pass":123456}
JQuery gets cross-domain JSON data
First refer to the jQuery library file:
<script src="http://apps.bdimg.com/libs/ jquery/1.9.0/jquery.min.js">
</script>
jQuery code:
var url="http://localhost:8000/user.php?jsoncallback=?"; $(function(){ $.getJSON(url,function(data){ alert (data.name); }) });
Server code (PHP):
<?php header('Content-Type:text/html;Charset=utf-8'); $arr = array( "name" => "xiaoming", "pass" => "123456"); echo $_GET['jsoncallback']."(".json_encode($arr).")"; ?>
The server returns a string (the parameter "jsoncallback" needs to be passed in):
jQuery19003894091040769696_1505708469340({"name":"xiaoming","pass":123456})
Explain that the value passed in by jQuery is different each time.
The difference between JQuery obtaining same-domain and cross-domain JSON data
From the above two examples, there are two differences between JQuery obtaining same-domain and cross-domain JSON data:
1) jQuery is written differently, and an additional parameter "jsoncallback= ?"
2) The writing method of the returned string on the server side is different. The incoming value of "'jsoncallback'" needs to be used when crossing domains. The constructed string format is: incoming value of jsoncallback (original JSON string), be careful to use Parentheses surround the original JSON string.
Summary
Through the introduction of this article, everyone should understand that to read JSON data across domains with jQuery, you first need to construct a special JSON string on the server side, otherwise it cannot be read. Fortunately, the construction method is very simple. The example in the text It's easy to understand at a glance.
jQuery + Ajax to obtain cross-domain JSON data
The previous example uses $.getJSON to obtain cross-domain JSON data. In fact, we can also use $.ajax method.
First reference the jQuery library file:
<script src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js">
</script>
jQuery code:
<script type="text/javascript"> $(function(){ $.ajax({ type: 'get', url: 'http://localhost:8000/user.php?jsoncallback=?', dataType: 'jsonp', jsonp: "jsoncallback", success: function(data) { alert("Username: "+ data.name+" Password: "+ data.pass); } }); }) </script>
Note in particular that dataType is jsonp and not json.