2

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

这就是我所拥有的。这是我的 html 页面上的 2 个文本区域。

<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(另一个文本区域)。它是计算出来的,但我不知道如何传回多个参数。这样做的方法是什么?谢谢你。

4

4 回答 4

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);

编辑 - 在回显数组之前还设置正确的标题。完成后,在客户端解析 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;
    }
}
于 2012-04-17T12:48:00.273 回答
2

研究 JSON,JavaScript 可以原生处理。这比任何类型的字符串拆分都要好,因为它确保输出不包含您将用于分解结果的一个或多个字符。

工作流程是这样的:

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

PHP 的 $array['me']='you' 在 JavaScript 中将是 array['me'] 。

于 2012-04-17T12:50:27.853 回答
0

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

例如页面的输出是:HelloWorld

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

并用那个分隔符分割它

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

于 2012-04-17T13:37:15.243 回答
0

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

于 2012-04-17T12:49:37.247 回答