如何使用AJAX返回两个字符串?

时间:2012-04-17 12:45:55

标签: php ajax

如何使用AJAX返回两个参数?

这就是我所拥有的。这是我的html页面上的2个textareas。

<textarea name="source" id="source" onkeyup="myfunc(this.value);}"></textarea>
<textarea name="res1" id="res1"></textarea>
<textarea name="res2" id="res2"></textarea>

Onkeyup事件从 .js文件调用 myfunc()函数。

myfunc()包含以下字符串:

...
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("res1").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("POST","ajax_file.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset= UTF-8");
xmlhttp.send("q="+encodeURIComponent(str));

结果, ajax_file.php 进行一些计算,计算q和p并返回q。字符串q返回textarea res1 。一切都很好,它工作正常。但是,我想将值 p 传递给 res2 (另一个textarea)。这是计算的,但我不知道如何传回多个参数。这样做的方法是什么? 谢谢。

4 个答案:

答案 0 :(得分:5)

最明显的方式(如果你想发送两个参数)是

xmlhttp.send("q="+encodeURIComponent(str)+"&p="+encodeURIComponent(str1));

如果要返回两个参数,请在php中使用数组并在json

中对其进行编码
$arr = array();

$arr['str1'] = $str1;
$arr['str2'] = $str2;
header('Content-type: application/json');
echo json_encode($arr);

EDIT - 在回显数组之前设置correcxt标头。完成后,在客户端上解析JSON

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var resp = JSON.parse(xmlhttp.responseText);
        document.getElementById("res1").innerHTML=resp.str1;
        document.getElementById("res1").innerHTML=resp.str2;
    }
}

答案 1 :(得分:2)

查看JSON,JavaScript可以本地处理。这比任何类型的字符串拆分都要好,因为它确保输出不包含用于爆炸结果的字符或字符。

工作流程是:

  • PHP将结果写入数组,然后使用json_encode()对其进行编码,并将其作为响应回显
  • Javascript使用array = JSON.parse(result)将其转换为可用的JavaScript对象,其中result是PHP的结果。

PHP的$ array ['me'] ='你'将成为JavaScript中的数组['me']。

答案 2 :(得分:0)

您可以发送带分隔符的字符串“Value1,Value2,Value3”,然后使用javascript split方法,或使用JSON:http://www.php.net/manual/en/function.json-encode.php

答案 3 :(得分:0)

ajax返回页面的整个输出,所以你不能用它返回两个字符串,但是你可以把那个字符串分成两个

例如页面的输出是:HelloWorld

现在你想要Hello和World分开,所以请输出如下:Hello,World OR Hello-World OR Hello | World

并将其与分隔符

分开

$(“PAGE”,{“var”:“value”},function(response){response.split(delimiter)})