繁体   English   中英

数组未与Ajax一起传递。

[英]Array not passing with ajax.

这是ajax调用的Java脚本代码。 在这种情况下, code变量获取ac程序代码,并将其传递到compiler.php页面。

function insert(){
        var code = document.getElementById("file_cont").value;
        var arr = new Array(code,"c");
        alert(arr[0]);
    var xmlhttp;
        if (window.XMLHttpRequest)
          {
          xmlhttp=new XMLHttpRequest();
          }
        else
          {
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }

        xmlhttp.onreadystatechange=function(){          
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                //window.location.assign("login.php");
                alert (xmlhttp.responseText);
            }
      }
    xmlhttp.open("POST","server_controlers/compiler.php?q="+JSON.stringify(arr),true);
    xmlhttp.send();
}

Ajax调用工作良好,但情况在php文件中。 我将jason数组解码为$arr变量。 但是,如果我echo这样echo $arr[0]为空。 但是,如果我不将code到Java脚本中的数组中,例如var arr = new Array("aaaa","c"); 它的作品很好。 当我发送带有code变量的数组时,可以告诉我这是什么问题。 这是php文件。

<?php
if(isset($_REQUEST["q"])){

    $arr = $_REQUEST["q"];
    $arr2 = json_decode($arr);

    echo $arr2[0];  
    /*$file = fopen("../temp_files/c/mmm.c","w");
    fwrite($file,"$arr[0]");
    fclose($file);
    shell_exec('gcc -ommm ../temp_files/c/mmm.c');
    system('mmm', $retval);*/
}else{

}

?>
server_controlers/compiler.php?q="+JSON.stringify(arr)

您的数据未设置为URL安全。 您说它包含c代码,这意味着它可能包含(例如) &字符,该字符会破坏查询字符串格式,并导致从其中提取JSON时无效。

您需要先通过encodeURIComponent运行数据,然后再将其放入URL。

server_controlers/compiler.php?q=" + encodeURIComponent(JSON.stringify(arr))

我认为您的请求类型为POST / GET的问题。 您在1中混洗了2个请求类型。另外,我如何看到您尝试发送get请求? 但在参数中,请使用POST类型。

您可以在这里找到有关GET请求的所有信息。

您也可以尝试更改您的php代码。 如果您需要使用POST

 <?php
     if($_POST){
     print($_POST);
     }
?>

之后,您可以使用数据数组完成所有您需要的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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