dongyouzhi7218 2017-03-14 17:57
浏览 37
已采纳

如何从Ajax调用param访问PHP中的数组?

I am making an Ajax call:

    $.ajax({
        url: "create_card.php",
        type: "GET",
        data: {deck: selection, data: $(input_form).serialize()}
    });

Initially, I was just using the array in the call, so I had data: $(input_form).serialize(), and I was using this code to get the data from the input form (card_info is an array of the named data in the input form):

    for($x = 0; $x < $array_length; $x++) {
        if(isset($_GET[$card_info[$x]])){
            $arg = $_GET[$card_info[$x]];
            $sql_query .= "\"" . $arg . "\"";
            if($x != $array_length - 1) {
                $sql_query .= ", ";
            } else {
                $sql_query .= ")";
            }
        }
    }

But now that I added the extra parameter to the Ajax call, I can't seem to access the data in the same way anymore. I've tried $_GET[data[$card_info[$x]]] but this did not work.

  • 写回答

1条回答 默认 最新

  • dtpoius74857 2017-03-14 18:24
    关注

    $(input_form).serialize() serializes data from your form to a string, kinda inputName1=inputValue1&inputName2=inputValue2&inputName3=inputValue3 and etc.

    Using

    data: {deck: selection, data: $(input_form).serialize()}
    

    means that you send to your server an object with two properties deck and data. On server this object will be converted to $_GET array with two keys: deck and data. And $_GET['data'] will hold a string with your previously serialized values.

    If you use print_r($_GET) you will see, what I'm talking about.

    So the solution is not to mix ways of sending data. Either you send a string, as @splash58 proposed:

    // here you have a string
    data: $(input_form).serialize() + '&deck=' + selection
    

    Or an object:

    // here you have an object
    data: {deck: selection, field1: $("#someId").val(), field2: $("#yaId").val(), /* etc */ }
    

    Where field1, field2 are keys and $("#someId").val(), $("#yaId").val() are methods which are used to get some values (in this case using ids).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起