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

Native JS implements ajax and ajax cross-domain requests

小云云
Release: 2018-01-05 10:39:50
Original
2698 people have browsed it

This article mainly shares with you an example of native JS implementing ajax and ajax cross-domain request. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

1. Native JS implements ajax

The first step is to obtain the XMLHttpRequest object

The second step is to set the status listening function

The third step is to open one Connection, true is an asynchronous request

Part 4: Send a request, you can send an object and a string, there is no need to pass data and send null

Step 5: In the listening function, judge readyState=4&&status=200 indicates that the request is successful

Step 6: Use responseText and responseXML to accept the response data, and use native JS to operate the DOM for display

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
 console.log(ajax.readyState);
 console.log(ajax.status);
 if(ajax.readyState==4 && ajax.status==200){
  console.log(ajax.responseText);
  console.log(ajax.responseXML);//返回不是XML,显示null
  console.log(JSON.parse(ajax.responseText));
  console.log(eval("("+ajax.responseText+")"));
  }
}
ajax.open("GET","h51701.json",true);
ajax.send(null);
Copy after login

2. Ajax cross-domain request

[Cross-domain request processing] Due to the same origin policy in JS. When requesting files with different protocol names, different port numbers, and different host names, it will violate the same origin policy and the request cannot be successful! Cross-domain processing is required!

1. Background PHP settings:

No settings are required in the front desk. Write a header in the requested PHP file in the background.

header("Access-Control-Allow-Origin:*");//表示允许哪些域名请求这个PHP文件,*表示所有域名都允许
Copy after login

2. Use src attribute + JSONP to achieve cross-domain

① Tags with src attributes have cross-domain functions! Therefore, you can use the src attribute of the script tag to request background data

<scriptsrc="http://127.0.0.1/json.php"type="text/javascript"charset="utf-8"></script>
Copy after login

② Since src will directly put the loaded content into the script tag after successfully loading the data

So, the background directly returns JSON The string will not be parsed in the script tag

Therefore, the background should return a return function name to the frontend and pass the JSON string as a parameter

Return to the background PHP file:

echo"callBack({$str})";
Copy after login
Copy after login

③The front desk receives the returned function and will call it directly in the script tag. Therefore, it is necessary to declare such a callback function as a callback for successful request.

function callBack(data){
  alert("请求成功");
  console.log(data);
 }
Copy after login

3. JQuery's ajax implementation JSONP

① When making an ajax request, set the dataType to "json"

② When returning from the backend, you still need to return Callback. However, when ajax sends a request, it will use the get request by default to send the return function name to the background. The background can use $_GET['callback'] to get the callback function name:

echo"{$_GET['callback']}({$str})";
Copy after login

③After the background returns, ajax still You can use success as a successful callback function:

success:function(data){}
Copy after login

Of course, the background can also return a callback function name at will.

echo"callBack({$str})";
Copy after login
Copy after login

As long as the request is successful, the front desk will automatically call this function. Similar to the ②③ steps in Article 2

Related recommendations:

AJAX cross-domain access-two effective solutions introduced_PHP tutorial

How to use native JS to implement Ajax GET POST request

AngularJS method to implement ajax request

The above is the detailed content of Native JS implements ajax and ajax cross-domain requests. 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
Popular Tutorials
More>
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!