如何在第二响应中显示有关ajax授权和cors的内容?

时间:2018-09-15 08:29:55

标签: javascript php jquery ajax cors

我已经在vps中建立了基本授权和cors。

curl -X选项-i http://111.111.111.111

HTTP/1.1 200 OK
Date: Sat, 15 Sep 2018 08:07:37 GMT
Server: Apache/2.4.6 (CentOS)
Access-Control-Allow-Origin: http://127.0.0.1
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With
Allow: OPTIONS,GET,HEAD,POST,TRACE
Content-Length: 0
Content-Type: httpd/unix-directory

curl -u xxxx:xxxx -i http://111.111.111.111/remote.php

HTTP/1.1 200 OK
Date: Sat, 15 Sep 2018 08:08:07 GMT
Server: Apache/2.4.6 (CentOS)
Access-Control-Allow-Origin: http://127.0.0.1
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With
Last-Modified: Sat, 15 Sep 2018 07:54:13 GMT
ETag: "24-575e43f02c324"
Accept-Ranges: bytes
Content-Length: 36


<?php
echo  '{"name","myname"}';
?>

您可以看到授权和cors处于良好状态。

我的本​​地目录/var/www/html中的test-ajax-cors.html。

<script src="http://127.0.0.1/jquery-3.3.1.js"></script>
<script>
function Ajax( ) {
    var url = 'http://111.111.111.111/remote.php';
    $.ajax(url, {
        type:"post",   
        crossDomain: "true",
        dataType:"json",
        beforeSend:function(xhr) {
            xhr.setRequestHeader('Authorization',"Basic " + btoa("xxxx:xxxx"))},
        success:function(response){
        data = JSON.stringify(response);
            alert(data);
            mytext = $("#remote");
            mytext.append(data);
        },
        error: function (e) {
            alert("error");
        } 
    });
};
</script>

<input type="button" value="show content" onclick="Ajax();">
<p id="remote">the content on remote webpage</p>

http://111.111.111.111中的remote.php。

cat /var/www/html/remote.php

<?php
echo  '{"name","myname"}';
?>

键入127.0.0.1/test-ajax-cors.html,单击show content
1.我收到警报信息:错误
2.remote.php被127.0.0.1/test-ajax-cors.html调用了两次(show content中的127.0.0.1/test-ajax-cors.html按钮仅被单击了一次)。

the first response 首次调用remote.php的时间,remote.php的存储库中没有内容。
第一个请求可能是CORS-preflight请求,浏览器发送不带任何Authorization标头的OPTIONS请求,在我的情况下,服务器向浏览器发送200状态代码,这意味着一切都处于良好状态。

enter image description here

remote.php在第二次调用remote.php时的响应内容。
如何使内容在第二响应中显示为127.0.0.1/test-ajax-cors.html
感谢Sally CJ的通知。

yum install mod_php
systemctl restart httpd

键入127.0.0.1/test-ajax-cors.html,然后单击show content
1.警告错误信息

enter image description here

2。remote.php被调用了两次,remote.php的所有响应都相同。

{"name","myname"}

enter image description here enter image description here

我所期望的是内容,为什么不能在网页127.0.0.1\test-ajax-cors.html中显示它,从而导致警报错误信息?

2 个答案:

答案 0 :(得分:4)

首先,由于您的PHP脚本未执行,并且响应仅返回了脚本的内容,因此您的服务器似乎未正确设置(我发现您已经用{{ 1}})。

第二,mod_php不是有效的{"name", "myname"}。您的回复应该为JSON,或者为了方便起见,您应该始终{"name": "myname"}一个json_encode数组,例如:

PHP

这样,您的<?php // Set the correct Content-Type // this helps when viewing in browser console, and is generally needed header('Content-Type: application/json'); // Create an array with needed response data $result = [ 'name' => 'myname' ]; // Convert PHP array to a correct JSON string and echo it echo json_encode($result); 将始终有效,或者至少您会看到可帮助您进行调试的错误。

更正答复后,您可以执行以下操作:

JSON

请注意,success: function(response, textStatus, jqXHR) { // var stringData = JSON.stringify(response); you don't need this // since jqXHR object already contains the raw response text // It's recommended to prefix variable name with $ // that way you will always know that it is a JQuery object var $mytext = $("#remote"); $mytext.text(jqXHR.responseText); // console.log(response); is better than alert // unless you really need to pause the script alert(response.name); } 足够聪明,可以查看请求是否为JQuery请求,因此您的回调仅应在第二个请求传递内容时才触发。

答案 1 :(得分:3)

@it_is_a_literature有关第一个问题(错误部分的警告),则应在php文件中设置标头( header('Content-Type:application / json'); < / strong>),并在回显中使用 json_encode 。对于两次函数调用,您应在函数ajax()的末尾返回false

Test.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function Ajax( ) {
    var url = 'http://localhost:855/remote.php';
    $.ajax(url, {
        type:"post",   
        crossDomain: "true",
        dataType:"json",
        beforeSend:function(xhr) {
            xhr.setRequestHeader('Authorization',"Basic " + btoa("xxxx:xxxx"))},
        success:function(response){
        data = JSON.stringify(response);
            alert(data);
            mytext = $("#remote");
            mytext.append(data);
        },
        error: function (e) {
            alert("error");
        }
    });
    return false;
};
</script>

<input type="button" value="show content" onclick="Ajax();">
<p id="remote">the content on remote webpage</p>

Response.php

<?php
header('Content-Type: application/json');
echo  json_encode(array("name","myname"));
?>

响应:

First hit to Resposne.php

no second function call