May 08, 2021 JSON
With regard to the concept of JSONP and why JSONP should be used, you can refer to the JSONP tutorial, the focus of this article is to demonstrate how the Ajax method in JQUERY can be called remotely through JSONP.
Let's start with the parameters of $.ajax:
On the server side we use MVC's ACTION to return the data
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
@{ 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 is found that the server-side Request.QueryString ("callback") returns a random function name. T his is set to JSONP format to pass the data
You can customize the function name during the transfer, as long as you use the jsonpCallback parameter.
<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>
Add1: Using AJAX to access the aspx page is the same as the asmx usage method, the difference is that the method in the aspx page must be static and asmx does not need to.
1. Create a new demo .aspx page.
2. First add a reference to the background file .aspx.cs the page.
using System.Web.Services;
3. Method calls without parameters.
Note that this version cannot be lower than .net framework 2.0. 2 .0 is not supported. Background code:
[WebMethod] public static string SayHello() { //一定是要静态方法,并且声明为[WebMethod] 前端才可以访问 return "Hello Ajax!";
JS code:
$(function() { $("#btnOK").click(function() { $.ajax({ //要用post方式 type: "Post", //方法所在页面和方法名 url: "Demo.aspx/SayHello", //没有参数也一定要传一个空参数 data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { //返回的数据用data.d获取内容 alert(data.d); }, error: function(err) { alert(err); } }); //禁用按钮的提交 return false; }); });
Page code:
<form id="form1" runat="server"> <div> <%--<asp:Button ID="btnOK" runat="server" Text="验证用户" />--%> <%--因为是异步,所以只能使用html,上面的服务器控件是错误的 可以测试下--%> <input id="btnOK" type="button" value="button" /> </div> </form>
Here's how it works:
3. There are parameter methods to call 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", //方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字 data: "{'str':'我是','str2':'XXX'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { //返回的数据用data.d获取内容 alert(data.d); }, error: function(err) { alert(err); } }); //禁用按钮的提交 return false; }); });
Here's how it works:
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) { //插入前先清空ul $("#list").html(""); //递归获取数据 $(data.d).each(function() { //插入结果到li里面 $("#list").append("<li>" + this + "</li>"); }); alert(data.d); }, error: function(err) { alert(err); } }); //禁用按钮的提交 return false; }); });
Page code:
<form id="form1" runat="server">
<div>
<asp:Button ID="btnOK" runat="server" Text="验证用户" />
</div>
<ul id="list">
</ul>
</form>
Run the result chart:
Here is a detailed list of AJAX parameters in Jquery:
The name of the argument | Type | Describe |
Url | String | (Default: Current page address) to send the requested address. |
type | String | (Default: "GET") request method ("POST" or "GET"), default to "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it. |
timeout | Number | Set the request time-out time in milliseconds. This setting overrides the global settings. |
async | Boolean | (default: true) By default, all requests are asynchronous. I f you need to send a sync request, set this option to false. Note that the sync request locks the browser and the user must wait for the request to complete before executing. |
beforeSend | Function |
You can modify the functions of the XMLHttpRequest object before sending a request, such as adding a custom HTTP header. T
he 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 the browser cache. |
complete | Function |
The callback function (called when the request succeeds or fails) after the request is completed. A
rgument: XMLHttpRequest object, success information string.
function (XMLHttpRequest, textStatus) { this; // the options for this ajax request } |
contentType | String | (Default: "application/x-www-form-urlencoded") the type of content encoding when sending information to the server. The default values are appropriate for most applications. |
data |
Object,
String |
Data sent to the server. W ill be automatically converted to the request string format. T he GET request is attached to the URL. R eview the processData option description to prevent this automatic conversion. M ust be in Key/Value format. I f it is an array, jQuery will automatically correspond to the same name for different values. Such as the "foo: " bar1", "bar2" , " , |
dataType | String |
The type of data expected to be returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on http package MIME information and pass the available values as callback function parameters: "xml": Returns the XML document, which can be processed by jQuery. "html": Returns plain text HTML information; "script": Returns plain text JavaScript code. Results are not automatically cached. "json": Returns JSON data. "jsonp": JSONP format. W hen a function is called in JSONP form, such as "myurl?callback=?" jQuery will be replaced automatically? Is the correct function name to execute the callback function. |
error | Function |
(default: This method is called when the automatic judgment (xml or html)) request fails. T
his method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the wrong object captured.
function (XMLHttpRequest, textStatus, errorThrown) { // 通常情况下textStatus和errorThown只有其中一个有值 this; // the options for this ajax request } |
global | Boolean | (default: true) whether to trigger a global AJAX event. S etting to false will not trigger a global AJAX event, such as ajaxStart or ajaxStop. Can be used to control different Ajax events |
ifModified | Boolean | (default: false) get new data only when the server data changes. Use the HTTP package Last-Modified header information to determine. |
processData | Boolean | (default: true) By default, the data sent is converted to an object (not technically a string) to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, set it to false. |
success | Function |
The callback function after the request was successful. T
his method has two parameters: the server returns the data and returns the state
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参数
}
});
});
});
I.
error: function (XMLHttpRequest, textStatus, errorThrown)
(silent: Automatically determines (xml or html)) when the request fails to call the time. T
here are three parameters: XMLHttpRequest object, error message, (optional) captured error object.
If an error occurs, the error message (the second argument) may be "timeout," "error," "notmodified, and parserror" in addition to null.
textStatus:
"timeout," "error," "notmodified" and "parserror."
Second, the error event returns the first argument XMLHttpRequest has some useful information:
XMLHttpRequest.readyState:
The status code
0 - (not initialized) the send() method has not been called
1 - (Loaded) The send() method has been called and the request is being sent
2 - The (load completed) send() method execution is complete and all responses have been received
3 - (Interaction) is parsing the response content
4 - (Complete) The response content resolution is complete and can be called on the client
Three, data: " data is empty must also be passed " otherwise returned in xml format. And prompt parserror.
Iv. Parserror exceptions also have a relationship with the Header type. a nd codeheader ('Content-type: text/html; charset=utf8');
V. XMLHttpRequest.status: