Home  >  Article  >  Web Front-end  >  How to implement ajax and ajax cross-domain requests in JS

How to implement ajax and ajax cross-domain requests in JS

亚连
亚连Original
2018-06-23 14:31:101308browse

The editor below will share 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 and take a look

1. Implement ajax with native JS

The first step is to obtain the XMLHttpRequest object

Step 2: Set up the status listening function

Step 3: Open a connection, true is an asynchronous request

Part 4: Send a request, you can send an object and a string, no need Pass data and send null

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

Step 6: Use responseText and responseXML to receive response data, and use native JS Manipulate 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);

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 PHP file requested in the background.

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

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>

② 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})";

③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);
 }

3. JQuery’s ajax implementation JSONP

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

② When the backend returns, the callback function still needs to be returned. 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[&#39;callback&#39;]}({$str})";

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

success:function(data){}

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

echo"callBack({$str})";

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

, I compiled the above for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement asynchronous image upload in javascript

How to implement the hidden element function in jquery

How to achieve password consistency in verification forms in jQuery

How to use array functions in JS

About how to use the picker component in WeChat mini program

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

Statement:
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