Home > Web Front-end > JS Tutorial > body text

Three ways jQuery uses JSONP to obtain cross-domain data

小云云
Release: 2018-05-23 09:22:13
Original
4390 people have browsed it

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数据
  }
});
Copy after login

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数据
});
Copy after login

The third method is to use the getScript method

//此时也可以在函数外定义foo方法
function foo(data){
  //处理data数据
}
$.getScript('http://www.a.com/user?id=123&callback=foo');
Copy after login

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(&#39;请求失败&#39;);
    }
  });
</script>
</head>
Copy after login

jsonp.php

<?
$data["age"] = $_GET[&#39;age&#39;];
$data["name"] = $_GET[&#39;name&#39;];
$data["statusCode"]="200";
$data["message"]="成功";
$tmp= json_encode($data); //json数据
echo $callback . &#39;(&#39; . $tmp .&#39;)&#39;; //返回格式,必需
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!