【问题标题】:Accessing $_POST data sent by Jquery/AJAX访问由 Jquery/AJAX 发送的 $_POST 数据
【发布时间】:2011-08-27 01:18:52
【问题描述】:

我正在使用这个功能:

function end_incident() {
    var dataString = 'name=Daniel&phone=01234123456';
    $.ajax({
        type: "POST",
        url: "http://www.example.co.uk/erc/end_incident.php",
        data: dataString,
        success: function(msg){ 
            alert('Success!'+dataString);
        }
    });
};

end_incident.php 发送信息,但我无法访问$_POST 变量。我试过这样做:

$name = $_POST['name'];
$phone = $_POST['phone'];

我做错了吗?

感谢您的帮助

【问题讨论】:

  • 我希望same origin policy 在这里不是问题。
  • @Salman A,这就是我的怀疑。

标签: php javascript jquery ajax post


【解决方案1】:

尝试将数据作为对象发送:

function end_incident() {
    $.ajax({
       type: "POST",
       url: "http://www.example.co.uk/erc/end_incident.php",
       data: { name: "Daniel", phone: "01234123456" },
       success: function(msg){ 
            alert('Success!');
       }
    });
};

【讨论】:

  • 该死,想发同样的东西!你速度更快 :) +1
  • 不,这不会有任何区别。 data 属性可以设置为对象(在这种情况下,它将被转换为查询字符串)或查询字符串格式的字符串。 See here.
  • 嗨,Richard D,感谢您的回复。我认为问题是我在我的 SQL 查询中遗漏了几个撇号,现在它正在工作,但我喜欢你使用的更好的布局,所以我会使用它:)
【解决方案2】:

确保您请求的网址与您的网站在同一来源,如果不是,则说明您遇到了跨站点脚本问题。只有这样:

  • 在浏览器中获得“更高”的访问权限/特权,即创建插件/扩展程序,或使用 Greasemonkey
  • 通过您自己的站点使用代理来获取文件请求:

    var getURL = "http://www.example.co.uk/erc/end_incident.php";
    $.ajax({
       type: "POST",
       url: "/get_url.php?url=" + encodeURIComponent(getURL),
       data: { name: "Daniel", phone: "01234123456" },
       success: function(msg){ 
           alert('Success!');
       }
    });
    

我建议您在 ajax 中添加一个 error 函数。令人惊讶的是有多少人只关注success 而从不处理错误!

error: function()
{
   console.log(arguments);
}

【讨论】:

  • +1 用于错误评论。但是实际上告诉用户发生了错误不是一个好主意吗?您永远不知道您的服务器或用户的 WIFI 何时关闭。 alert("Could not connect to the server. Please check your network connection or try again later."); ...或者更干净的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
相关资源
最近更新 更多