javascript 访问 Jquery/AJAX 发送的 $_POST 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6028142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:11:57  来源:igfitidea点击:

Accessing $_POST data sent by Jquery/AJAX

phpjavascriptjqueryajaxpost

提问by Daniel H

I am using this function:

我正在使用这个功能:

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);
        }
    });
};

to send information to end_incident.php, but I'm not able to access the $_POSTvariables. I've tried doing it like this:

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

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

Am I doing something wrong?

难道我做错了什么?

Thanks for any help

谢谢你的帮助

回答by Richard Dalton

Try sending the data as an object:

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

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!');
       }
    });
};

回答by Gary Green

Make sure the url your requesting for is within the same originof your site, if it isn't, you've got a cross-site scripting issue. Only way around that:

确保您请求的 url与您网站的来源相同,如果不是,则您遇到了跨站点脚本问题。唯一的办法是:

  • Getting "higher" access/priveledges within the browser, i.e. create an add-on/extension, or use Greasemonkey
  • Use a proxy through your own site to get the request for the file:

    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!');
       }
    });
    
  • 在浏览器中获得“更高”的访问权限/特权,即创建附加组件/扩展程序,或使用 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!');
       }
    });
    

I recommend you add a errorfunction to your ajax. It's suprising how many people just focus on successand never process an error!

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

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