jQuery Ajax 发布数据格式

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

Ajax post data format

jqueryajax

提问by Daniel Mason

Is it possible to format the data like so?

是否可以像这样格式化数据?

{name: $('#elementId').text()}

I have tried many options, but nothing seems to work. I get ajax success but no data is sent to the server. The return value is null.

我尝试了很多选择,但似乎没有任何效果。我获得 ajax 成功,但没有数据发送到服务器。返回值为空。

$.ajax({
    type: "POST",
    url: "ReportTest.php",
    data: {machineId: $('#FormOverviewMachineID').text()},
    success: function(output){
        console.log(jQuery.parseJSON(output));
    }
})

Any help on this would be fantastic. I feel like I'm pretty close.

对此的任何帮助都会很棒。我觉得我很接近。

Thanks.

谢谢。

Edit:

编辑:

My PHP is like so (for testing):

我的 PHP 是这样的(用于测试):

$MachineID = $_POST['machineID'];
print_r($MachineID);

I can also print the values to the console before using them in the ajax request like so

我也可以在像这样在 ajax 请求中使用它们之前将值打印到控制台

machineIdTest = $('#FormOverviewMachineID').text();
console.log("MachineID: "+machineIdTest);

This returns the value fine.

这将返回值罚款。

Final Edit

最终编辑

Okay okay, I was dumb but thanks for the responses.

好吧好吧,我很笨,但感谢您的答复。

Typo: machineId=/= machineID

错别字:machineId=/= machineID

And thanks for the mention about parsing the response in JSON.

并感谢您提到解析 JSON 中的响应。

Cheers everyone!

大家加油!

回答by Reinstate Monica Cellio

Change your script to this...

将您的脚本更改为此...

$.ajax({
    type: "POST",
    url: "ReportTest.php",
    data: {machineID: $('#FormOverviewMachineID').text()},
    success: function(output){
        console.log(output);
    }
});

I've only made 1 small change. You originally passed the data variable machineId, but then looked for machineIDin PHP. They're different names in your post (uppercase/lowercase D).

我只做了 1 个小改动。您最初传递了数据变量machineId,但后来machineID在 PHP 中查找。它们在您的帖子中是不同的名称(大写/小写 D)。

回答by Alberto De Caro

Initialize the data outside the ajax call:

在ajax调用外初始化数据:

var machineIdValue = $('#FormOverviewMachineID').text();
$.ajax({
    type: "POST",
    url: "ReportTest.php",
    data: {machineId: machineIdValue},
    success: function(output){
        console.log(jQuery.parseJSON(output));
    }
})

Breakpoint on the machineIdValue assignment line and then check its value in the console.

在 machineIdValue 分配行上断点,然后在控制台中检查其值。

回答by Rahul Goutham

yes possible

是的可能

$('#FormOverviewMachineID').val() instead of $('#FormOverviewMachineID').text();

回答by Jitendra Pancholi

Its a table cell so you can use $('#FormOverviewMachineID').html()to get its value.

它是一个表格单元格,因此您可以使用它 $('#FormOverviewMachineID').html()来获取其值。

Try and let me know.

试着让我知道。