【问题标题】:Ajax pass parameter in data send to php数据中的Ajax传递参数发送到php
【发布时间】:2021-02-16 03:33:27
【问题描述】:

假设我有一个带有 onclick 功能的元素,它在单击时会触发 prompt()。 一旦用户填写了提示,它还会触发一个 ajax 请求,该请求会将带有 post 类型的提示值发送到 php 页面以获得响应。

所以我有这个代码:

<i class="fas fa-wrench text-warning editmode" id="Pseudo" onclick="goEdit(this.id)" title="Edit my pseudo"></i>

function goEdit(id) {
        console.log(id); // The console log here print me "Pseudo" and that's what i want
        $(document).ready(function() {
            let userchange = prompt();
            $.ajax({
                type: 'POST',
                url: 'traitements/traitement-profil.php',
                data: {
                    id: userchange

// The problem is here ! I want to send a $_POST['Pseudo'] that contains the answer of the prompt. 
// But that doesn't work.
// Instead if i a do a print($_POST) in my php page i get this as a response in my alert below:
// array(1) { ["id"]=> array(1) { ["id"]=> string(24) "Answer of the prompt here"

                },
                dataType: 'text',
                success: function(data) {
                    alert(data);
                }
            });
        });
    }

我需要我的 $_POST 等于所单击按钮的 id 的值的原因是因为我需要在同一页面上有多个像这样的按钮,每个按钮都有自己的用途,但总是做同样的事情。只有 $_post 参数会改变每个参数,这个参数必须等于点击按钮的 id

【问题讨论】:

    标签: javascript php jquery ajax post


    【解决方案1】:

    更新:如果您想要的是数据对象中的动态键,您可以通过以下方式实现:

    var data = {};
    data[id] = userchange;
    
    $.ajax({
       type: 'POST',
       url: 'traitements/traitement-profil.php',
       data: data,
       dataType: 'text',
       success: function(data) {
          alert(data);
       }
    });
    

    您似乎误解了如何构造JSON object

    您传递的数据应如下所示:

    data: {
       id: id,
       answer: userchange
    },
    

    然后在 PHP 中您将能够通过以下方式访问它们:

     $_POST['id'] // contains "Pseudo"
     $_POST['answer'] // contains "Answer of the prompt here"
    

    【讨论】:

    • 这不是我想要的。我希望 $_POST 的参数等于我的按钮的 id 并包含提示的答案
    • 啊,我明白了,对不起,我误会了。检查更新的答案:)
    • 一种作品,但 php 中的所有内容都包含在这样的双数组中:array(1) { ["data"]=>array(1) { ["Pseudo"]=> string( 4)“提示的答案”}}有没有办法在没有“数据”数组的情况下将所有内容都放在一个数组中?如果没有,我如何访问 ["pseudo"] 并在数组 ["data"] 中分别回答?
    • 没关系!语法有问题。现在完美运行:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2019-06-26
    • 2017-04-18
    相关资源
    最近更新 更多