Home >Web Front-end >JS Tutorial >How to call the ajax method remotely through JSONP in jquery_jquery

How to call the ajax method remotely through JSONP in jquery_jquery

WBOY
WBOYOriginal
2016-05-16 16:50:071240browse

There are many tutorials on the Internet about the concept of JSONP and why to use JSONP. This section mainly demonstrates how to remotely call the ajax method in JQUERY through JSONP

First introduce the parameters of $.ajax

type: request method GET/POST

url: request address

async: Boolean type, the default is true to indicate whether the request is asynchronous, if false it indicates synchronous.

dataType: the returned data type

jsonp: the parameter name passed to the request handler or page to obtain the jsonp callback function name (generally the default is: callback)

jsonpCallback: Customized jsonp callback function name. The default is a random function name automatically generated by jQuery. You can also write "?", and jQuery will automatically process the data for you

success: Call the successfully executed function

error: Exception handling function

1. Example 1

On the server side, we use MVC's ACTION to return data

Copy code The code is as follows:

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

public ActionResult Index()
{
returnView();
}

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

}

The client uses jsonp to transmit data
Copy code The code is as follows:

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





After clicking the submit button, it was found that Request.QueryString["callback"] on the server side returned a random function name . In this way, it is set to JSONP format to transfer data

2. Custom function name

You can customize the function name during the transfer process, just use the jsonpCallback parameter.

jsonp: Indicates the parameters passed, the default is callback, we can also customize it. The server segment uses this parameter to obtain the customized function name. The server obtains Request.QueryString["callback"] like this:

jsonpCallback represents the passed parameter value, which is the function name of the callback, which is a custom name.
Copy code The code is as follows:


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