PHP handles Ajax requests and Ajax cross-origin problems _ php instance-PHP source code

Source: Internet
Author: User
Tags php server
This article mainly introduces the relevant information about how PHP handles Ajax requests and Ajax cross-domain issues. it is very good and has reference value, for more information about how to use PHP to handle Ajax requests and cross-origin Ajax problems, see this article.

PHP determines if it is an Ajax request

We know that when sending an ajax request, we can use the XMLHttpRequest object to create custom header information. in the jquery framework, for the $. ajax, $. get, or $. when the post method requests the webpage content, it will pass a HTTP_X_REQUESTED_WITH parameter to the server. in php, it is to determine whether the request is an ajax request at the header layer.$_SERVER['HTTP_X_REQUESTED_WITH']Judgment. Generally, $ _ SERVER['HTTP_X_REQUESTED_WITH']The default value isXMLHttpRequest,$_SERVER['HTTP_X_REQUESTED_WITH']You can also customize the creation and useXMLHttpRequest.setRequestHeader(name,value).

Example: The front-end page sends a common ajax request to the backend test. php.

$.ajax({  type: "GET",  url: 'test.php',  success: function(data) {    console.log(data);  }});

The test. php server can determine whether the request is an Ajax asynchronous request and then respond to the request based on business needs.

The following is a simple code for verifying whether the server test. php is an ajax request:

function isAjax() {  return @$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ? true : false;}if (isAjax()) {  echo 'Ajax Request Success.';} else {  echo 'No.';}

Ajax initiates a JSONP cross-origin request

We can use jQuery's JSONP method to implement cross-origin ajax requests, and php on the server also needs to handle them accordingly. that is to say, php must request and return data in a certain format with the front-end page.

Example: The front-end page initiates a JSONP request:

$.ajax({  type: "get",  data: "random="+Math.random(),  url: "http://demo.jb51.net/phpajax/jsonp.php",  dataType: "jsonp",  jsonp: "callback",  success: function(data) {   console.log(data);  },  error: function() {   console.log('Request Error.');  }});

We will find that the ajax request parameters include Ype: "jsonp" and jsonp: "callback". This indicates that the request is jsonp and a callback is returned. Of course, we can also customize callback functions, such as jsonpCallback: "success_jsonpCallback"

You can also simply write it as follows:

jQuery.getJSON('http://demo.jb51.net/phpajax/jsonp.php?callback=?",{ random: Math.random()}, function(data){ console.log(data);});

Php backend service code can be written as follows (note the format returned by the output ):

$data = array(  'rand' => $_GET['random'],  'msg' => 'Success');echo $_GET['callback'].'('.json_encode($data).')';

Ajax cross-origin request: CORS

CORS, also known as Cross-Origin Resource Sharing, is short for Cross-Origin Resource Sharing. Suppose we want to use Ajax to retrieve key data from a.com pages to B .com pages. Generally, this request is not allowed due to the same-origin policy, the browser will also return the "source mismatch" error, so there is a "cross-origin" statement. But we also have a solution. we can add a line of code in the header information of B .com:

header("Access-Control-Allow-Origin: *");

When the header we set is the above information, we can process and respond to any request from the server. then we can see its header information settings in the debugging tool, the message "* Access-Control-Allow-Origin: *" in the red box indicates that CORS has been enabled. to restrict requests for only a domain name, you can:

header("Access-Control-Allow-Origin: https://www.php1.cn/");

Example: Cross-origin request data through CORS

$.ajax({  type: "get",  data: "random="+Math.random(),  url: "http://demo.jb51.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.');  }});

Add the following code to ajax. php under another website domain name:

header("Access-Control-Allow-Origin: https://www.php1.cn/");$data = array(  'rand' => $_GET['random'],  'msg' => 'Success');echo json_encode($data);

The above section describes how to use PHP to process Ajax requests and cross-origin Ajax requests. I hope it will help you. if you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for the script home website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.