PHP handles ajax requests and ajax cross-domain

PHP中文网
Release: 2023-03-15 17:22:02
Original
1578 people have browsed it

When sending an ajax request, you can create custom header information through the xmlHttpRequest object. In the jquery framework, when requesting web content through its $.ajax, $.get, or $.post method , it will pass an HTTP_X_REQUESTED_WITH parameter to the server. In PHP, it is judged at the header level whether it is an ajax request, and the corresponding judgment is based on $_SERVER['HTTP_X_REQUESTED_WITH']. Generally, $_SERVER['HTTP_X_REQUESTED_WITH'] defaults to XMLHttpRequest. $_SERVER['HTTP_X_REQUESTED_WITH'] can also be customized and created using XMLHttpRequest.setRequestHeader(name,value). Example: The front-end page sends a normal ajax request to the back-end test.php.

$.ajax({ type: "GET", url: 'test.php', success: function(data) { console.log(data); } }); 服务端test.php可以判断该请求是不是Ajax异步请求,然后根据业务需求做出响应的回应。 以下是服务端test.php的简单验证是否为ajax请求的代码: function isAjax() { return @$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ? true : false; } if (isAjax()) { echo 'Ajax Request Success.'; } else { echo 'No.'; } Ajax发起JSONP跨域请求 我们通过jQuery的JSONP方式可以实现跨域ajax请求,服务端php也需要做出相应的处理,也就是说php这边必须和前端页面按照一定的格式请求和返回数据。 示例:前端页面发起JSONP请求: $.ajax({ type: "get", data: "random="+Math.random(), url: "http://demo.thinkphp.net/phpajax/jsonp.php", dataType: "jsonp", jsonp: "callback", success: function(data) { console.log(data); }, error: function() { console.log('Request Error.'); } }); 我们会发现,ajax请求参数中有dataType: "jsonp"和jsonp: "callback",这个就表明了我要请求的是jsonp,并且会有回调callback返回。当然,我们也可以自定义回调函数,如jsonpCallback:"success_jsonpCallback" 还可以简单的写成: jQuery.getJSON('http://demo.thinkphp.net/phpajax/jsonp.php?callback=?",{ random: Math.random() }, function(data){ console.log(data); }); php后端服务代码可以这样写(注意输出返回的格式): $data = array( 'rand' => $_GET['random'], 'msg' => 'Success' ); echo $_GET['callback'].'('.json_encode($data).')'; Ajax跨域请求:CORS CORS,又称跨域资源共享,英文全称Cross-Origin Resource Sharing。假设我们想使用Ajax从a.com的页面上向b.com的页面上要点数据,通常情况由于同源策略,这种请求是不允许的,浏览器也会返回“源不匹配”的错误,所以就有了“跨域”这个说法。但是我们也有解决办法,我们可以再b.com的页面header信息中增加一行代码: header("Access-Control-Allow-Origin: *"); 当我们设置的header为以上信息时,任意一个请求过来之后服务端我们都可以进行处理和响应,那么在调试工具中可以看到其头信息设置,其中见红框中有一项信息是“*Access-Control-Allow-Origin:* ”,表示我们已经启用CORS,如果要限制只允许某个域名的请求,可以这样: header("Access-Control-Allow-Origin: http://www.thinkphp.com"); 示例:通过CORS跨域请求数据 $.ajax({ type: "get", data: "random="+Math.random(), url: "http://demo.thinkphp.net/phpajax/ajax.php", dataType: "json", success: function(data) { console.log(data); $("#result_3").html(data.msg+':'+data.rand); }, error: function() { $("#result_3").html('Request Error.'); } }); 我们在另一个网站域名下的ajax.php加上这样的代码: header("Access-Control-Allow-Origin: http://www.thinkphp.com"); $data = array( 'rand' => $_GET['random'], 'msg' => 'Success' ); echo json_encode($data);
Copy after login


The above is the detailed content of PHP handles ajax requests and ajax cross-domain. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!