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

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误