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 爬取豆瓣电影相关处理
  • ¥15 手机淘宝抓清除消息接口
  • ¥15 C#无selenium
  • ¥15 LD衰减计算的结果过大
  • ¥15 用机器学习方法帮助保险公司预测哪些是欺诈行为
  • ¥15 计算300m以内的LD衰减
  • ¥15 数据爬取,python
  • ¥15 怎么看 cst中一个面的功率分布图,请说明详细步骤。类似下图
  • ¥15 为什么我的pycharm无法用pyqt6的QtWebEngine
  • ¥15 FOR循环语句显示查询超过300S错误怎么办