简体   繁体   中英

Pass object to PHP through AJAX

I was wondering if it is possible to pass an array to a php function using the jQuery AJAX function. I have the following as my javascript

arr_data = {
    field01: "data 01",
    field02: "data 02",
    field03: "data 03",
    field04: "data 04"
}

$.ajax({
    url: "scripts/php/phpfunc.php",
    type: "GET",
    dataType: "json",
    data: {
        'action': "exec_find",
        'field01': arr_data["field01"],
        'field02': arr_data["field02"],
        'field03': arr_data["field03"],
        'field04': arr_data["field04"]
    },
    success: function(result) {
        // continue program
    },
    error: function(log) {
        // handle error
    }
});

When I try to do the following though

arr_data = {
    field01: "data 01",
    field02: "data 02",
    field03: "data 03",
    field04: "data 04"
}

$.ajax({
    url: "scripts/php/phpfunc.php",
    type: "GET",
    dataType: "json",
    data: {
        'action': "exec_find",
        'data': arr_data
    },
    success: function(result) {
        // continue program
    },
    error: function(log) {
        // handle error
    }
});

I receive it in the PHP as "Array". How can I correctly send the object so that it is usable by the PHP function?

Please try to pass the array in the format of json. Then use the get the json in your php and access the json array.

<script>

arr_data = {
    field01: "data 01",
    field02: "data 02",
    field03: "data 03",
    field04: "data 04"
}
var  myJsonString= JSON.stringify(arr_data);
$.ajax({
    url: "scripts/php/phpfunc.php",
    type: "GET",
    dataType: "json",
    data: {
        'action': "exec_find",
        'data': myJsonString
    },
    success: function(result) {
        // continue program
    },
    error: function(log) {
        // handle error
    }
});
</script>

this is your java script. and below is the php

$dataJson=json_decode($_GET['data']);

here you can get the json array and loop through it and do what ever you want.

Please have try at this. This is working in my case.

from the second ajax you can access the data based on the property names like: $_GET['data']['field01']

$_GET['data'] is the js object converted in php in a associative array

try this :

$.ajax({
    url: "scripts/php/phpfunc.php",
    method: "POST",
    dataType: "json",
    data: {
        'action': "exec_find",
        'data': arr_data.serialize()
    },

serialize()

http://api.jquery.com/serialize/

convert your array in string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM