This article mainly introduces the three methods of jQuery using JSONP to achieve cross-domain data acquisition. It also compares and analyzes three common operation techniques of jsonp cross-domain data acquisition in the form of examples. Friends who need it can refer to it. I hope it can help everyone.
The first method is to set the dataType to 'jsonp' in the ajax function
$.ajax({ dataType: 'jsonp', url: 'http://www.a.com/user?id=123', success: function(data){ //处理data数据 } });
The second method It is implemented using getJSON. Just add the callback=? parameter to the address.
$.getJSON('http://www.a.com/user?id=123&callback=?', function(data){ //处理data数据 });
The third method is to use the getScript method
//此时也可以在函数外定义foo方法 function foo(data){ //处理data数据 } $.getScript('http://www.a.com/user?id=123&callback=foo');
Example walkthrough:
index.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>jsonp</title> <script src="jquery-1.8.0.min.js"></script> <script> $.ajax({ type : "post", url : "jsonp.php?name=zhaoxiace&age=30", dataType : "jsonp", jsonp: "callbackParam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback) jsonpCallback:"callbackFunction",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名 success : function(data){ console.log(data.statusCode + "/" + data.message + "/" + data.name + "/" + data.age); }, error:function(){ alert('请求失败'); } }); </script> </head>
jsonp.php
<? $data["age"] = $_GET['age']; $data["name"] = $_GET['name']; $data["statusCode"]="200"; $data["message"]="成功"; $tmp= json_encode($data); //json数据 echo $callback . '(' . $tmp .')'; //返回格式,必需 ?>
Related Recommended:
html5 How to carry out cross-domain communication
jQuery Jsonp cross-domain simulation search engine example sharing
Native JS implements ajax and ajax cross-domain requests
The above is the detailed content of Three ways jQuery uses JSONP to obtain cross-domain data. For more information, please follow other related articles on the PHP Chinese website!