使用 Ajax 将 Javascript 变量传递给 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6130662/
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:36:07  来源:igfitidea点击:

Passing Javascript Variable to PHP using Ajax

phpjavascriptajaxjquery

提问by Liam

I'm working on an existing script at the moment which uses Ajax, something I've never worked with before. I have a variable set in my javascript file which gets its value from an input field on my page. I need to use Ajax to post this to my PHP page only I've no idea where to start,

我目前正在处理一个使用 Ajax 的现有脚本,这是我以前从未使用过的。我在我的 javascript 文件中设置了一个变量,它从我页面上的输入字段中获取其值。我需要使用 Ajax 将其发布到我的 PHP 页面,但我不知道从哪里开始,

Im not sure what code you would need to see, but My javascript/AJAX code is, the variable I need to pass is 'var credoff'

我不确定您需要查看什么代码,但我的 javascript/AJAX 代码是,我需要传递的变量是“var credoff”

$(".getPoint").click(function () {
    var theid = $(this).attr("id");
    var onlyID = theid.split("_");
    var onlyID = onlyID[1];
    var credoff = parseInt($(this).children('input.credoff:hidden').val());

    $.ajax({
        url: 'do.php',
        type: 'POST',
        data: "userID=" + onlyID,
        success: function (data) {
            if (data != "success1" && data != "success5") {
                $("#" + theid).text(data);
            } else {

                $("#thediv_" + onlyID).fadeOut("slow");
                $('#creditsBalance').fadeOut("slow");
                newbalance = parseInt($('#creditsBalance').text());

Wouldit have to be in this format?

必须是这种格式吗?

data: "userID=" + onlyID,
"credoff=" + credoff

回答by silex

...
data: {
    userId: onlyID,
    credoff: credoff
},
...

回答by Liam

Or you can do this:

或者你可以这样做:

data: "userID=" + onlyID + "&credoff=" + credoff

don't forget the ampersand! &

不要忘记&符号!&