How does the ajax method in jquery make remote calls through JSONP

For the concept of JSONP and why you should use JSONP, you can refer to the JSONP tutorial . The focus of this article is to demonstrate how the Ajax method in JQUERY can be remotely invoked through JSONP.

$.ajax parameters

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 it is false, it means synchronous. 
  • dataType: the returned data type 
  • jsonp: The parameter name passed to the request handler or page to obtain the name of the jsonp callback function (usually the default is: callback) 
  • jsonpCallback: custom jsonp callback function name, the default is the 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 

code show as below:

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); 
  } 
} 

The client uses jsonp to transfer data 

code show as below:

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

<script src="~/Scripts/jquery-1.7.1.min.js"type="text/javascript"> </script> 
<script type="text/javascript"> 
functionSendData() 
{ 
$.ajax({ 
type: "get", 
async: false, 
url: "/home/ReturnJson", 
dataType: "jsonp", 
success: function(data){ 
alert(data.name); 
}, 
error: function(){ 
alert('fail'); 
} 
}); 
} 
</script> 
<input type="button" value="提交" onclick="SendData();"/> 

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

2. Custom function name 

You can customize the function name during the transfer process, as long as you use the jsonpCallback parameter. 

  • jsonp: Indicates the parameter passed, the default is callback, we can also customize it, the server segment obtains the custom function name through this parameter, and the server obtains Request.QueryString["callback"] in this way 
  • jsonpCallback: Indicates the passed parameter value, that is, the function name of the callback, which is a custom name. 

code show as below:

<script type="text/javascript"> 
functionSendData() { 
$.ajax({ 
type: "get", 
async: false, 
url: "/home/ReturnJson", 
dataType: "jsonp", 
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) 
jsonpCallback: "receive",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据 
success: function(data) { 
alert(data.name); 
}, 
error: function() { 
alert('fail'); 
} 
}); 
} 

functionreceive(data) { 
alert(data.age); 
} 
</script> 

jQuery AJAX implements calling page background method

Add1: Using AJAX to access aspx pages is the same as using asmx, the difference is that the methods in aspx pages must be static methods, but asmx does not.

1. Create a new demo.aspx page.
2. First add a reference to the background file demos.aspx.cs of the page.

using System.Web.Services;

3. Method calls without parameters.

Attention everyone, this version cannot be lower than .net framework 2.0. 2.0 is not supported. Background code:

[WebMethod]     
public static string SayHello()     
{     
//It must be a static method, and it must be declared as [WebMethod] before the front end can access it
return "Hello Ajax!";       

JS code:

$(function() {     
    $("#btnOK").click(function() {     
        $.ajax({     
            //To use the post method      
            type: "Post",     
            //The page where the method is located and the method name      
            url: "Demo.aspx/SayHello",    
            //If there is no parameter, you must pass an empty parameter
            data: "{}",   
            contentType: "application/json; charset=utf-8",     
            dataType: "json",     
            success: function(data) {     
                //The returned data uses data.d to get the content      
                alert(data.d);     
            },     
            error: function(err) {     
                alert(err);     
            }     
        });     
    
        //Disable submit button      
        return false;     
    });     
});    

Page code:

<form id="form1" runat="server">
    <div>
        <%--<asp:Button ID="btnOK" runat="server" Text="Authenticate User" />--%>
         <%--Because it is asynchronous, you can only use html, the above server control is wrong, you can test it--%>
        <input    id="btnOK" type="button" value="button" /> 
    </div>
</form>

The running effect is as follows:

3. There is a parameter method to call the background code:

[WebMethod]     
public static string GetStr(string str, string str2)     
{     
    return str + str2;     
} 

JS code:

$(function() {     
    $("#btnOK").click(function() {     
        $.ajax({     
            type: "Post",     
            url: "demo.aspx/GetStr",     
            //The method of passing parameters must be written correctly, str is the name of the formal parameter, and str2 is the name of the second formal parameter      
            data: "{'str':'I am','str2':'XXX'}",     
            contentType: "application/json; charset=utf-8",     
            dataType: "json",     
            success: function(data) {     
                //The returned data uses data.d to get the content      
                  alert(data.d);     
            },     
            error: function(err) {     
                alert(err);     
            }     
        });     
    
        //Disable submit button      
        return false;     
    });     
});    

The running effect is as follows:

4. Return the array method
background code:

[WebMethod]     
public static List<string> GetArray()     
{     
    List<string> li = new List<string>();     
    
    for (int i = 0; i < 10; i++)     
        li.Add(i + "");     
    
    return li;     
}    

JS code:

$(function() {     
    $("#btnOK").click(function() {     
        $.ajax({     
            type: "Post",     
            url: "demo.aspx/GetArray",     
            contentType: "application/json; charset=utf-8",     
            dataType: "json",     
            success: function(data) {     
                //Clear ul before inserting      
                $("#list").html("");     
    
                // get data recursively      
                $(data.d).each(function() {     
                    //Insert result into li      
                    $("#list").append("<li>" + this + "</li>");     
                });     
    
                alert(data.d);     
            },     
            error: function(err) {     
                alert(err);     
            }     
        });     
    
        //Disable submit button      
        return false;     
    });     
}); 

Page code:

<form id="form1" runat="server">
<div>
    <asp:Button ID="btnOK" runat="server" Text="验证用户" />
</div>
<ul id="list">
</ul>
</form>

Running result graph:

The following is a detailed list of AJAX parameters in Jquery:

parameter name type describe
url String (default: current page address) The address to send the request to.
type String (Default: "GET") Request method ("POST" or "GET"), default is "GET". Note: Other HTTP request methods such as PUT and DELETE can also be used, but only supported by some browsers.
timeout Number Set the request timeout in milliseconds. This setting overrides the global setting.
async Boolean (Default: true) By default, all requests are asynchronous. Set this option to false if you need to send synchronous requests. Note that the synchronous request will lock the browser, and other operations of the user must wait for the request to be completed before they can be executed.
beforeSend Function Functions that modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
  this; // the options for this ajax request
}
cache Boolean (Default: true) jQuery 1.2 new feature, set to false will not load request information from browser cache.
complete Function Callback function after the request is completed (both called when the request succeeds or fails). Parameters: XMLHttpRequest object, success message string.
function (XMLHttpRequest, textStatus) {
  this; // the options for this ajax request
}
contentType String (Default: "application/x-www-form-urlencoded") The content encoding type when sending messages to the server. The default value is suitable for most applications.
data Object,
String
Data sent to the server. Will be automatically converted to request string format. GET requests will be appended to the URL. See the processData option description to disable this automatic conversion. Must be in Key/Value format. If it is an array, jQuery will automatically assign the same name to different values. For example {foo:["bar1", "bar2"]} translates to '&foo=bar1&foo=bar2'.
dataType String

The expected data type returned by the server. If not specified, jQuery will automatically return responseXML or responseText according to the HTTP packet MIME information, and pass it as a callback function parameter, available values:

"xml": Returns an XML document, which can be processed with jQuery.

"html": Returns plain text HTML information; contains script elements.

"script": Returns plain text JavaScript code. Results are not automatically cached.

"json": returns JSON data.

"jsonp":  JSONP  format. When using  the JSONP  form to call the function, such as "myurl?callback=?" jQuery will automatically replace the ? with the correct function name to execute the callback function.

error Function (default: auto-judgment(xml or html)) This method will be called when the request fails. This method takes three parameters: the XMLHttpRequest object, the error message, and the (possibly) caught error object.
function (XMLHttpRequest, textStatus, errorThrown) {
  // Usually only one of textStatus and errorThown has a value
  this; // the options for this ajax request
}
global Boolean (Default: true) Whether to fire global AJAX events. Set to false to not trigger global AJAX events such as ajaxStart or ajaxStop. Can be used to control different Ajax events
ifModified Boolean (Default: false) Fetch new data only when server data changes. Use the HTTP packet Last-Modified header information to judge.
processData Boolean (default: true) By default, the data sent will be converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to false if you want to send DOM tree information or other information that you don't want converted.
success Function Callback function after successful request. This method has two parameters: server return data, return status
function (data, textStatus) {
  // data could be xmlDoc, jsonObj, html, text, etc...
  this; // the options for this ajax request
}


code:

$(document).ready(function() {
            jQuery("#clearCac").click(function() {
                jQuery.ajax({
                    url: "/Handle/Do.aspx",
                    type: "post",
                    data: { id: '0' },
                    dataType: "json",
                    success: function(msg) {
                        alert(msg);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest.status);
                        alert(XMLHttpRequest.readyState);
                        alert(textStatus);
                    },
                    complete: function(XMLHttpRequest, textStatus) {
                        this; // 调用本次AJAX请求时传递的options参数
                    }
                });
            });
        });

一、error:function (XMLHttpRequest, textStatus, errorThrown) { } 
(默 认: 自动判断 (xml 或 html)) 请求失败时调用时间。参数有以下三个:XMLHttpRequest 对象、错误信息、(可选)捕获的错误对象。如果发生了错误,错误信息(第二个参数)除了得到null之外,还可能是"timeout", "error", "notmodified" 和 "parsererror"。

textStatus:

 "timeout", "error", "notmodified" 和 "parsererror"。

二、error事件返回的第一个参数XMLHttpRequest有一些有用的信息:

XMLHttpRequest.readyState:

状态码 

0 - (未初始化)还没有调用send()方法 

1 - (载入)已调用send()方法,正在发送请求 

2 - (载入完成)send()方法执行完成,已经接收到全部响应内容 

3 - (交互)正在解析响应内容 

4 - (完成)响应内容解析完成,可以在客户端调用了

三、data:"{}", data为空也一定要传"{}";不然返回的是xml格式的。并提示parsererror.

四、parsererror的异常和Header 类型也有关系。及编码header('Content-type: text/html; charset=utf8');

五、XMLHttpRequest.status:

  • 1xx-信息提示  
    这些状态代码表示临时的响应。客户端在收到常规响应之前,应准备接收一个或多个1xx响应。  
    • 100-继续。  
    • 101-切换协议。  
  • 2xx-成功  
    这类状态代码表明服务器成功地接受了客户端请求。  
    • 200-确定。客户端请求已成功。  
    • 201-已创建。  
    • 202-已接受。  
    • 203-非权威性信息。  
    • 204-无内容。  
    • 205-重置内容。  
    • 206-部分内容。  
  • 3xx-重定向  
    客户端浏览器必须采取更多操作来实现请求。例如,浏览器可能不得不请求服务器上的不同的页面,或通过代理服务器重复该请求。  
    • 301-对象已永久移走,即永久重定向。  
    • 302-对象已临时移动。  
    • 304-未修改。  
    • 307-临时重定向。  
  • 4xx-客户端错误  
    发生错误,客户端似乎有问题。例如,客户端请求不存在的页面,客户端未提供有效的身份验证信息。400-错误的请求。  
    • 401-访问被拒绝。IIS定义了许多不同的401错误,它们指明更为具体的错误原因。这些具体的错误代码在浏览器中显示,但不在IIS日志中显示:  
    • 401.1-登录失败。  
    • 401.2-服务器配置导致登录失败。  
    • 401.3-由于ACL对资源的限制而未获得授权。  
    • 401.4-筛选器授权失败。  
    • 401.5-ISAPI/CGI应用程序授权失败。  
    • 401.7–访问被Web服务器上的URL授权策略拒绝。这个错误代码为IIS6.0所专用。  
    • 403-禁止访问:IIS定义了许多不同的403错误,它们指明更为具体的错误原因:  
    • 403.1-执行访问被禁止。  
    • 403.2-读访问被禁止。  
    • 403.3-写访问被禁止。  
    • 403.4-要求SSL。  
    • 403.5-要求SSL128。  
    • 403.6-IP地址被拒绝。  
    • 403.7-要求客户端证书。  
    • 403.8-站点访问被拒绝。  
    • 403.9-用户数过多。  
    • 403.10-配置无效。  
    • 403.11-密码更改。  
    • 403.12-拒绝访问映射表。  
    • 403.13-客户端证书被吊销。  
    • 403.14-拒绝目录列表。  
    • 403.15-超出客户端访问许可。  
    • 403.16-客户端证书不受信任或无效。  
    • 403.17-客户端证书已过期或尚未生效。  
    • 403.18-在当前的应用程序池中不能执行所请求的URL。这个错误代码为IIS6.0所专用。  
    • 403.19-不能为这个应用程序池中的客户端执行CGI。这个错误代码为IIS6.0所专用。  
    • 403.20-Passport登录失败。这个错误代码为IIS6.0所专用。  
    • 404-未找到。  
    • 404.0-(无)–没有找到文件或目录。  
    • 404.1-无法在所请求的端口上访问Web站点。  
    • 404.2-Web服务扩展锁定策略阻止本请求。  
    • 404.3-MIME映射策略阻止本请求。  
    • 405-用来访问本页面的HTTP谓词不被允许(方法不被允许)  
    • 406-客户端浏览器不接受所请求页面的MIME类型。  
    • 407-要求进行代理身份验证。  
    • 412-前提条件失败。  
    • 413–请求实体太大。  
    • 414-请求URI太长。  
    • 415–不支持的媒体类型。  
    • 416–所请求的范围无法满足。  
    • 417–执行失败。  
    • 423–锁定的错误。  
  • 5xx-服务器错误  
    服务器由于遇到错误而不能完成该请求。  
    • 500-内部服务器错误。  
    • 500.12-应用程序正忙于在Web服务器上重新启动。  
    • 500.13-Web服务器太忙。  
    • 500.15-不允许直接请求Global.asa。  
    • 500.16–UNC授权凭据不正确。这个错误代码为IIS6.0所专用。  
    • 500.18–URL授权存储不能打开。这个错误代码为IIS6.0所专用。  
    • 500.100-内部ASP错误。  
    • 501-页眉值指定了未实现的配置。  
    • 502-Web服务器用作网关或代理服务器时收到了无效响应。  
    • 502.1-CGI应用程序超时。  
    • 502.2-CGI应用程序出错。application.  
    • 503-服务不可用。这个错误代码为IIS6.0所专用。  
    • 504-网关超时。  
    • 505-HTTP版本不受支持。  

FTP  

  • 1xx-肯定的初步答复   
    这些状态代码指示一项操作已经成功开始,但客户端希望在继续操作新命令前得到另一个答复。   
    • 110重新启动标记答复。   
    • 120服务已就绪,在nnn分钟后开始。   
    • 125数据连接已打开,正在开始传输。   
    • 150文件状态正常,准备打开数据连接。   
  • 2xx-肯定的完成答复   
    一项操作已经成功完成。客户端可以执行新命令。200命令确定。   
    • 202未执行命令,站点上的命令过多。   
    • 211系统状态,或系统帮助答复。   
    • 212目录状态。   
    • 213文件状态。   
    • 214帮助消息。   
    • 215NAME系统类型,其中,NAME是AssignedNumbers文档中所列的正式系统名称。   
    • 220服务就绪,可以执行新用户的请求。   
    • 221服务关闭控制连接。如果适当,请注销。   
    • 225数据连接打开,没有进行中的传输。   
    • 226关闭数据连接。请求的文件操作已成功(例如,传输文件或放弃文件)。   
    • 227进入被动模式(h1,h2,h3,h4,p1,p2)。   
    • 230用户已登录,继续进行。   
    • 250请求的文件操作正确,已完成。   
    • 257已创建“PATHNAME”。   
  • 3xx-肯定的中间答复   
    该命令已成功,但服务器需要更多来自客户端的信息以完成对请求的处理。331用户名正确,需要密码。   
    • 332需要登录帐户。   
    • 350请求的文件操作正在等待进一步的信息。   
  • 4xx-瞬态否定的完成答复   
    该命令不成功,但错误是暂时的。如果客户端重试命令,可能会执行成功。421服务不可用,正在关闭控制连接。如果服务确定它必须关闭,将向任何命令发送这一应答。   
    • 425无法打开数据连接。   
    • 426Connectionclosed;transferaborted.   
    • 450未执行请求的文件操作。文件不可用(例如,文件繁忙)。   
    • 451请求的操作异常终止:正在处理本地错误。   
    • 452未执行请求的操作。系统存储空间不够。   
  • 5xx-永久性否定的完成答复   
    该命令不成功,错误是永久性的。如果客户端重试命令,将再次出现同样的错误。500语法错误,命令无法识别。这可能包括诸如命令行太长之类的错误。   
    • 501在参数中有语法错误。   
    • 502未执行命令。   
    • 503错误的命令序列。   
    • 504未执行该参数的命令。   
    • 530未登录。   
    • 532存储文件需要帐户。   
    • 550未执行请求的操作。文件不可用(例如,未找到文件,没有访问权限)。   
    • 551请求的操作异常终止:未知的页面类型。   
    • 552请求的文件操作异常终止:超出存储分配(对于当前目录或数据集)。   
    • 553未执行请求的操作。不允许的文件名。   
  • 常见的FTP状态代码及其原因   
    • 150-FTP使用两个端口:21用于发送命令,20用于发送数据。状态代码150表示服务器准备在端口20上打开新连接,发送一些数据。   
    • 226-命令在端口20上打开数据连接以执行操作,如传输文件。该操作成功完成,数据连接已关闭。   
    • 230-客户端发送正确的密码后,显示该状态代码。它表示用户已成功登录。   
    • 331-客户端发送用户名后,显示该状态代码。无论所提供的用户名是否为系统中的有效帐户,都将显示该状态代码。   
    • 426-命令打开数据连接以执行操作,但该操作已被取消,数据连接已关闭。   
    • 530 - This status code means that the user cannot log in because the username and password combination is invalid. If you are logged on with a user account, you may have mistyped your username or password, or you may have chosen to allow only anonymous access. If you log in with an anonymous account, IIS may be configured to deny anonymous access.   
    • 550-The command was not executed because the specified file is not available. For example, the file being GET'd does not exist, or trying to PUT a file into a directory to which you do not have write permissions.

Guess you like

Origin blog.csdn.net/cdming/article/details/130097986