You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery AJAX发送POST数据到PHP接口传值错误如何解决?

问题原因

你的AJAX请求参数传递格式不符合后端接口要求,具体有两个错误:

  1. $.ajax的data字段语法错误,没有按照键值对结构传递参数
  2. 后端通过json_decode(file_get_contents("php://input"))读取JSON格式的请求体,你没有指定请求的内容类型为JSON,也没有把参数序列化为JSON字符串

修复方案

修改你的update.js代码如下:

$(document).on("click", ".add-menuItem-button", function () {
    var id_comanda = $(this).attr("data-id_comanda");
    var id_menu = $(this).attr("data-id_menu");

    $.ajax({
        url: "http://localhost/projects/programmazione_web/api/dettagli_comanda/create.php",
        type: "POST",
        // 封装为符合要求的对象后序列化为JSON字符串
        data: JSON.stringify({
            id_comanda: id_comanda,
            id_menu: id_menu
        }),
        // 指定请求内容类型为JSON
        contentType: 'application/json',
        success: function (result) {
            // added to order, notify
            bootbox.alert("Aggiunto alla comanda");
        },
        error: function (xhr, resp, text) {
            // show error to console
            console.log(xhr, resp, text);
            bootbox.alert("Errore");
        }
    });
// 补充原代码遗漏的闭合括号
});

额外优化建议

  • 可以用$(this).data('id_comanda')代替attr("data-id_comanda")读取自定义data属性,是jQuery推荐的写法,代码更简洁
  • 生产环境部署时建议把接口地址的域名端口部分去掉,改用相对路径,避免跨域和部署后地址变动的问题

内容的提问来源于stack exchange,提问作者Sergio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 12:39:01