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

Cross-domain requests: jQuery's ajax jsonp usage solution

高洛峰
Release: 2017-01-09 10:50:01
Original
1341 people have browsed it

Directly executing the error method prompts an error - ajax jsonp has not been used before, and the understanding of it is similar to that of ordinary ajax requests, and there is no in-depth understanding of it; this error occurred, after debugging several times (check the background code and js part of the property settings) still doesn't work, which makes me feel very surprised and puzzled. Therefore, I decided to carefully study the use of ajax jsonp, and share the learning experience of the final successful test with everyone!
First, post the code that can be successfully executed:
(page part)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head> 
<title>Untitled Page</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 
jQuery(document).ready(function(){ 
$.ajax({ 
type : "get", 
async:false, 
url : "ajax.ashx", 
dataType : "jsonp", 
jsonp: "callbackparam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback) 
jsonpCallback:"success_jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名 
success : function(json){ 
alert(json); 
alert(json[0].name); 
}, 
error:function(){ 
alert(&#39;fail&#39;); 
} 
}); 
var a="firstName Brett"; 
alert(a); 
}); 
</script> 
</head> 
<body> 
</body> 
</html>
Copy after login


(Handler part)

<%@ WebHandler Language="C#" Class="ajax" %> 
using System; 
using System.Web; 
public class ajax : IHttpHandler { 
public void ProcessRequest (HttpContext context) { 
context.Response.ContentType = "text/plain"; 
string callbackFunName = context.Request["callbackparam"]; 
context.Response.Write(callbackFunName + "([ { name:\"John\"} ] )"); 
} 
public bool IsReusable { 
get { 
return false; 
} 
} 
}
Copy after login

(Request packet capture screenshot)

跨域请求之jQuery的ajax jsonp的使用解惑

function success_jsonpCallback(data) 
{ 
success(data); 
}
Copy after login

More cross-domain requests Please pay attention to the PHP Chinese website for related articles on the use of jQuery's ajax jsonp!


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