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

jquery中的ajax方法怎样通过JSONP进行远程调用_jquery

WBOY
Release: 2016-05-16 16:50:07
Original
1165 people have browsed it

关于JSONP的概念和为什么要使用JSONP网上已经有很多教程,这一节主要演示下在JQUERY中的ajax方法怎样通过JSONP进行远程调用

首先介绍下$.ajax的参数

type:请求方式 GET/POST

url:请求地址

async:布尔类型,默认为true 表示请求是否为异步,如果为false表示为同步。

dataType:返回的数据类型

jsonp:传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)

jsonpCallback:自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据

success:调用成功执行的函数

error:异常处理函数

1.示例1

服务器端我们采用MVC的ACTION来返回数据

复制代码 代码如下:

public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
returnView();
}

public ActionResult ReturnJson()
{
string callback = Request.QueryString["callback"];
string json = "{'name':'张三','age':'20'}";
string result = string.Format("{0}({1})", callback, json);
returnContent(result);
}

}

客户端使用jsonp来传输数据
复制代码 代码如下:

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}





点击提交按钮后,发现服务器端的Request.QueryString["callback"]返回一个随机函数名。这样就被设置成JSONP格式来传递数据了

2.自定义函数名

可以在传递过程中自定义函数名,只要使用jsonpCallback参数就可以了。

jsonp:表示传递的参数,默认为callback,我们也可以自定义,服务器段通过此参数,获取自定义的函数名称,服务器这样获取 Request.QueryString["callback"]

jsonpCallback表示传递的参数值,也就是回调的函数名称,这是自定义的名称。
复制代码 代码如下:


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!