使用JSON(Crossdomain)将数据发送到php

时间:2013-08-28 09:32:47

标签: php javascript ajax json

我的代码是 server1 ,PHP代码是 server2 。两台服务器是分开的。这段代码有什么问题?

var hr = new XMLHttpRequest();
hr.open("POST", "http://www.3675design.com/Clients/hl/developers/cyber/itgetbetter/email/index.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
    if (hr.readyState == 4 && hr.status == 200) {
        var data = JSON.parse(hr.responseText);
        for (var obj in data) {
            document.getElementById("conformation_and_error_header").innerHTML = "Video";
            document.getElementById("conformation_and_error_body").innerHTML = "Share yor video";

            $(document).ready(function () {
                $(".inline_popup_display_2").colorbox({
                    inline: true,
                    width: "50%"
                });
            });
        }
    }
}
hr.send("name=" + name + "&mail=" + mail + "&youtube=" + youtube + "&comments=" + comments + "");

1 个答案:

答案 0 :(得分:0)

在PHP代码中,您可以添加允许跨域访问的响应标头:

header("Access-Control-Allow-Origin:*");
在JS代码中,如果你想发布一个json字符串而不是k-v,你应该更改你的请求标题:

//hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.setRequestHeader("Content-type", "application/json");