Home  >  Article  >  Web Front-end  >  jquery中ajax跨域方法实例分析_jquery

jquery中ajax跨域方法实例分析_jquery

WBOY
WBOYOriginal
2016-05-16 15:24:461006browse

本文实例分析了jquery中ajax跨域。分享给大家供大家参考,具体如下:

JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问

方法一: jsonp之 getJSON

js

var url = "http://localhost/mytest/jsonp_php.php?callback=?";
$.getJSON(url, {
  "age": 21,
  "name": "kitty"
}, function (data) {
  alert("name:" + data.name + ", age:" + data.age);
});

php

<&#63;php 
  $age=$_GET["age"];
  $name=$_GET["name"];
  $jsondata = "{age:$age, name:'$name'}";
  echo $_GET['callback'].'('.$jsondata.')';
&#63;>

二jsonp之$.ajax

js

$.ajax({
  type: 'GET',
  url: 'http://localhost/mytest/jsonp_php.php',
  dataType: "jsonp",
  jsonp: "callback5",
  jsonpCallback:"flightHandler",
  data: {
    "age": 21,
    "name": "kitty"
  },
  success: function (data) {
    alert("name:" + data.sd + ", age:" + data.aa)
  }
})

php

<&#63;php
  $age=$_GET["age"];
  $name=$_GET["name"];
  $ary=array("sd"=>"sdfg","aa"=>23);
   $jsondata=json_encode($ary);
  echo $_GET['callback5'].'('.$jsondata.')';
&#63;>

希望本文所述对大家jQuery程序设计有所帮助。

Statement:
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