【问题标题】:Send javascript arrays via ajax without using jquery通过 ajax 发送 javascript 数组而不使用 jquery
【发布时间】:2016-12-04 12:34:38
【问题描述】:

我有一个 javascript 数组,其中包含“正确”、“错误”等值。 我想使用 ajax 将此数组发送到我的 php 文件。但我不熟悉如何。 这是我到目前为止所尝试的......我想在没有 jquery 的情况下做到这一点。

var hold=[];
    for(t = 0;t <= 10; t++){ 
    answers_Arr = document.getElementsByName("question"+t);
    for (k = 0; k < answers_Arr.length; k++){
        if(answers_Arr[k].checked){
            hold[t] = answers_Arr[k].value;
            //document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
            break;
        }else{
            hold[t] = "no";
            continue;

        }
    }
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState==4  &&  xmlhttp.status==200)
    {
    document.getElementById("test1").innerHTML= xmlhttp.responseText;
    }
}

xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();

}

【问题讨论】:

    标签: javascript php arrays ajax


    【解决方案1】:

    这里是通过 AJAX 发送带有 POST 的 json 字符串的示例:

    var jsonString = JSON.stringify(hold);
    var xmlhttp = new XMLHttpRequest();
    
    xmlhttp.onreadystatechange = function() {
        //
    }
    
    xmlhttp.open("POST","result.php",true);
    xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.send(jsonString);
    

    避免使用 GET 方法发送 json 字符串,因为如果请求字符串过长,浏览器会抛出错误。

    现在在您的 php 脚本中,您将拥有 $_POST 中的所有数据

    编辑:看起来在某些版本的 php 上,具有其他 Content-type 的请求,如 application/json,$_POST 具有空值。要解决此问题,您可以这样做:

    $_POST = json_decode(file_get_contents('php://input'));
    

    【讨论】:

    • 谢谢。你能帮我用 php 脚本来检索这个吗?
    • 您应该拥有 $_POST 中的所有数据,就像您通过普通表单发送它一样。如果您不确定变量包含什么,您可以随时使用print_r($_POST); 打印它的内容
    • 我尝试使用 print_r($_POST);但它只打印'array()'。就是这样。
    • 我很好奇你用的是什么版本的php?你也可以试试这个:$_POST = json_decode(file_get_contents('php://input'));
    • &lt;?php include 'Connect.php'; $myarray= $_POST; print_r($_POST); 这是我试过的
    【解决方案2】:

    替换这一行

    xmlhttp.open("GET","result.php?res="+hold[],true);
    

    xmlhttp.open("GET","result.php?res="+jsonString,true);
    

    【讨论】:

    • 它仍然显示“res”未定义。而且当我在 php. 中显示数组时,它显示 null
    • 你的意思是你的 php 脚本中没有定义?
    • 这是我在我的 php 脚本中使用的,'$res = json_decode(stripslashes($_GET['res'])); echo json_encode($res);'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2012-01-24
    • 2013-04-22
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多