doutu1889 2012-04-17 12:45
浏览 273
已采纳

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

How to return two parametres using AJAX?

Here is what I have. Here are 2 textareas on my html page.

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

Onkeyup event calls myfunc() function from .js file.

myfunc() contains such strings:

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

As result, ajax_file.php makes some computations, calculates q and p and returns q. String q returned to textarea res1. Everything is OK, it works fine. But, I would like to pass the value p to res2 (another textarea) as well. It's calculated, but I don't know how to pass back more than one parameter. What's the way to do that? Thank you.

  • 写回答

4条回答 默认 最新

  • duancheng8000 2012-04-17 12:48
    关注

    the most obvious way (if you want to send two parameters) is

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

    if you want to return two parameters, use an array in php and encode it in json

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

    EDIT - set also the correcxt headers before echoing the array. After doing that, parse the JSON on the client

    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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?