首页 > 解决方案 > 数据未完成的 JQuery Ajax Post

问题描述

我有以下内容,但由于未显示警报,因此 postdata 似乎存在问题。如何正确创建 postdata 以包含所选选项?

HTML

<select id="reportTypeChosen" onchange="reportType()">
    <option value="1">Opt1</option>
    <option value="2">Opt2</option>
    <option value="3">Opt3</option>
</select>

脚本

function reportType() {
    var sel = document.getElementById("reportTypeChosen");
    var choosenType = sel.options[sel.selectedIndex].value;
    var postdata = "{choice: " + choosenType + "}";
    $.post("setreporttype.php", function(postdata, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
}

这会在控制台中出现错误:未定义数据

我也试过:

function reportType() {
    var sel = document.getElementById("reportTypeChosen");
    var choosenType = sel.options[sel.selectedIndex].value;
    $.post("setreporttype.php", function({choice: choosenType}, status){
        alert("Data: " + data + "\nStatus: " + status);
}

这也不起作用,但没有任何错误。

更新: postdata 在不正确的地方。更正版本如下:

function reportType() {
    var sel = document.getElementById("reportTypeChosen");
    var choosenType = sel.options[sel.selectedIndex].value;
    $.post("setreporttype.php", {choice: choosenType}, function(data, status){
 alert("Data: " + data + "\nStatus: " + status);
    });
}

标签: jquerypost

解决方案


您正在使用带有两个参数 URl 和一个成功回调的 post 函数,因此您正在发送一个空帖子(尽管关于您的调试,请更加清楚),然后在回复中查找您要发送的数据从回调。

你可能想要这个:

$.post({my-url}, {data-to-send}, function({data-from-server}){
  doStuff(data-from-server)
});

推荐阅读