无法通过ajax将javascript对象传递给php

我已经在javascript中创建了一个新数组,我正在从函数中添加索引,然后将数组传递给ajaxCall函数,我尝试将其转换为json并通过ajax将其发送到php文件,但是变量json总是空的。 我一直在阅读很多关于如何通过ajax发送javascript_encoded的javascript对象,看起来这是这样做的方法,但显然我没有readed enought或者有一些我一直在想的东西。 无论如何我是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); } ... 

您正在尝试将数组用作哈希值,因此未设置值。

而不是设置

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

  string(6) "valueA" ["checkbox2"]=> string(6) "valueB" } */ ?> 

如果你只有两个较小的参数,我会保持简单并发出一个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); }