【问题标题】:Send string data with jQuery AJAX使用 jQuery AJAX 发送字符串数据
【发布时间】:2021-09-29 18:22:30
【问题描述】:

我正在为大学做一个网络项目,所以我是第一次处理 AJAX。 基本上,我想为餐厅员工创建一个平台来管理订单、餐桌、预订等。

这是向订单添加菜肴的窗口:

到目前为止,我只通过提交表单与我的 API 进行了交互。我想在这里实现的是,当我点击 + 或 - 符号时,必须将相关菜插入数据库。

下面我只放几段与我的问题有关的代码。

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",
            data: id_comanda, id_menu,
            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");
            }
        });

以下是 PHP 函数。

create.php:

// prepare object
$dettagli_comanda = new dettagliComanda($db);

// get id of record to be edited
$data = json_decode(file_get_contents("php://input"));

// make sure data is not empty
if (
    !empty($data->id_comanda) &&
    !empty($data->id_menu)
) {
    // set property values
    $dettagli_comanda->id_comanda = $data->id_comanda;
    $dettagli_comanda->id_menu = $data->id_menu;

    // create new record
    if ($dettagli_comanda->create()) {
        // set response code - 201 created
        http_response_code(201);

        // tell the user
        echo json_encode(array("message" => "Operazione eseguita con successo."));
    }
    // if unable to add new record
    else {
        // set response code - 503 service unavailable
        http_response_code(503);

        // tell the user
        echo json_encode(array("message" => "Non è stato possibile eseguire l'operazione, riprova più tardi."));
    }
}

// if data is empty
else {
    // set response code - 400 bad request
    http_response_code(400);

    // tell the user
    echo json_encode(array("message" => "C'è stato un problema durante l'elaborazione della richiesta, controlla i dati e riprova."));
}

在 object.php 文件中创建函数:

// create new record
    function create()
    {
        // sql query
        $query = "INSERT INTO dettagli_comanda 
                    SET id_comanda = :id_comanda,
                        id_menu = :id_menu,
                        stato = '0'";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->id_comanda = htmlspecialchars(strip_tags($this->id_comanda));
        $this->id_menu = htmlspecialchars(strip_tags($this->id_menu));

        // bind values
        $stmt->bindParam(":id_comanda", $this->id_comanda);
        $stmt->bindParam(":id_menu", $this->id_menu);

        // execute query
        if ($stmt->execute()) {
            return true;
        }
        return false;
    }

我已经使用 Postman 测试了 PHP 函数,它们可以正常工作。 我确定问题出在 AJAX 调用中,更具体地说是在传递值中。 有人知道如何帮助我吗?

另外,如果我能以某种方式提高我的问题的一致性,请告诉我。

【问题讨论】:

    标签: javascript php jquery ajax


    【解决方案1】:

    您需要将参数作为对象传递。见下文:

     $(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",
                data: {comanda: id_comanda, menu: id_menu },
                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");
                }
            });
    

    另外,请确保您在 data 键下方提交内容类型,如下所示:

    contentType: "application/json; charset=utf-8",
    

    【讨论】:

    • 他们如何在 PHP 中获取发布的值也存在问题。他们应该(根据此代码)使用:$_POST['comanda']$_POST['menu'] 获取它,而不是使用 file_get_contents('php://input') 并将其解析为 json(它不会是)。顺便说一句,我不是反对者。
    • @AttemptedMastery 我试过那个解决方案,但是控制台打印的错误是 400。所以$data->id_comanda$data->id_menu 是空的。
    • @MagnusEriksson 例如,我应该将$data = json_decode(file_get_contents("php://input")); 替换为$data = $_POST['comanda']; 吗?
    • @Sergio 是的,这样做并检查我的初始帖子 - 我添加了一个编辑。
    • @Sergio - 好吧,那是不正确的。数据应该看起来像它在这个答案中的样子:data: {comanda: id_comanda, menu: id_menu }。在 ajax 请求中,data: 属性是要发送的有效负载,而data2: 不是可以执行任何操作的有效属性。请阅读您正在使用的函数的文档(jquery ajax 和 PHP)
    【解决方案2】:

    首先,我感谢@AttemptedMastery 和@MagnussEriksson 的帮助和耐心。 花了一段时间,但我找到了不同的解决方案,但他们的帮助很有启发性。

    基本上,问题在于var id_comanda = $(this).attr("data-id_comanda");var id_menu = $(this).attr("data-id_menu"); 中存储的值是字符串,而json_decode(file_get_contents("php://input")); 接受JSON 内容类型。

    解决方法是对Ajax调用里面的数据使用JSON.stringify()函数,如下:

    $(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",
                contentType: "application/json",
                data: JSON.stringify({
                    id_comanda: id_comanda,
                    id_menu: id_menu
                }),
                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");
                }
            });
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多