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

How to remotely call the ajax method in jquery through JSONP_jquery

WBOY
Release: 2016-05-16 16:53:28
Original
1628 people have browsed it

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 "?", 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 the 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三','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, I 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 indicates passing The parameter value is the callback function name, which is a custom name.
Copy code The code is as follows:


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