Home  >  Article  >  php教程  >  When Ajax cross-domain posts data to the PHP program, the PHP program is always executed twice.

When Ajax cross-domain posts data to the PHP program, the PHP program is always executed twice.

WBOY
WBOYOriginal
2016-08-08 08:49:47948browse

The php program is deployed on IIS7. When submitting data through ajax, two problems are encountered. One is cross-domain. A php program will always be executed twice.

The solution to the first problem is from Baidu. Just add the following lines of code:

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

header("Access-Control-Allow-Headers: x-requested-with,content-type");

header('Access-Control-Allow-Methods: OPTIONS,POST,GET');

Actually, you can also set it directly in IIS without adding code. Just select the site directly, then click on the http response header on the right, configure it directly in it, and that's it. As shown in the picture:

For the second question, there has been no result from Baidu, so I had to FQ and use Google. I understood it at once, and then followed the clues to find it, and finally figured it out.

In the CORS .net cross-domain solution, it is introduced like this (http://jingyan.baidu.com/article/03b2f78c190ad25ea237ae33.html)

The same request requires two methods with the same request address, one marked "POST" and the other marked "OPTIONS". The entity method is the method marked "POST". The "OPTIONS" method here does not need to do any logical operations and The return value is void (in fact, the OPTIONS request is a verification of the browser. When sending a POST request with parameters, the browser will first send an OPTIONS request and verify that the request header information and the response header information are consistent before actually launching the POST request)

The packet capture found that it was indeed the case. The browser generated two requests, OPTIONS service/service.php HTTP/1.1 and POST /service/service.php HTTP/1.1

I originally wanted to return void directly when requesting OPTIONS as mentioned in the article, but when I see the php configuration, I can directly restrict the action. I tried it and it worked. Now the ajax is cross-domain and the php program is only executed once.

The configuration method in IIS is as follows: Find the PHP program site, you can also select server settings, click the handler mapping on the right, find PHP, click Edit, in the pop-up dialog box, click Request Limit, then select the predicate, click one of the predicates below , enter GET and POST as prompted. To save trouble, I used the default option (all predicates) before, so I encountered this problem. As shown in the picture:

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