我已经在javascript中创建了一个新数组,并且我正在从函数中添加值索引,然后将数组传递给ajaxCall函数,我尝试将其转换为json并将其发送到php文件通过ajax,但变量json总是空的。我已经阅读了很多关于如何通过ajax json_encoded发送javascript对象的内容,看起来这是这样做的方法,但显然我还没有想到或者有些东西我已经失踪了。无论如何我都是javascript中的新手,任何帮助都会被贬低。
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);
}
...
答案 0 :(得分:0)
如果你只有两个较小的参数,我会保持简单并发出一个http get请求。如有必要,请对您的参数进行编码。
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
答案 1 :(得分:0)
您正在尝试将数组用作哈希值,因此未设置值..
而非设置
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"
}
*/
?>