无法通过ajax将javascript对象传递给php
我在javascript中创建了一个新数组,我正在从函数中添加值,然后将数组传递给ajaxCall函数,我尝试将其转换为json并通过ajax将其发送到php文件,但变量json总是空的。我一直在阅读很多关于如何通过ajax发送javascript_encoded的javascript对象,看起来这是这样做的方法,但显然我没有readed enought或者有一些我一直在想的东西。无论如何我是javascript中的新手,任何帮助都会被贬低。
I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
您正在尝试使用您的阵列作为哈希,所以没有设置值..
You are trying to use your array as a hash, so the values are not being set..
而不是设置
var advancedFormVars = new Array();
尝试设置
var advancedFormVars = {};
示例
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>