jQuery Ajax Post因访问控制而未发布数据

时间:2014-02-25 11:21:59

标签: javascript php jquery ajax post

我尝试将表单内容发布到远程托管的PHP页面,这是我的代码:

$.ajax({
        type: "POST",
        url: "http://url/page.php",
        data: formstring, // formstring=form.serialze();
        dataType: "text",
        success: function (data) { alert(data);},
        error: function () {}
    });

我用:

启动了我的PHP文件
<?php
header('Access-Control-Allow-Origin: *');

print("hi");
die();

我在Firebug中只看到OPTIONS请求:

Response Headers:
Access-Control-Allow-Orig...    *
Connection  Keep-Alive
Content-Encoding    gzip
Content-Length  22
Content-Type    text/html
Date    Tue, 25 Feb 2014 11:14:22 GMT
Keep-Alive  timeout=15, max=99
Server  Apache
Vary    Accept-Encoding
X-Powered-By    PHP/5.3.3-7+squeeze18

Request Headers:
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-us,fr;q=0.7,en;q=0.3
Access-Control-Request-He...    x-requested-with
Access-Control-Request-Me...    POST
Cache-Control   no-cache
Connection  keep-alive
Host    www.domain.tld
Origin  http://212.xxx.252.xxx
Pragma  no-cache
User-Agent  Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0

1 个答案:

答案 0 :(得分:0)

为此你应该在你的ajax请求中启用cors

实施例,

 $.ajax({
        url: "http://url/page.php",
        type: "POST",
        crossDomain: true,
        data: formstring,
        success: function (response) {

        },
        error: function (xhr, status) {
            alert("error");
        }
    });