如何使用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.

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

You could either send a delimited string "Value1,Value2,Value3" and then use the javascript split method, or use JSON: http://www.php.net/manual/en/function.json-encode.php

Look into JSON, which JavaScript can handle natively. This is better than any sort of string splitting, since it makes sure the output does not include character or characters that you would use for exploding the result.

Workflow is this:

  • PHP writes result into an array and then encodes it with json_encode() and echos this as a response
  • Javascript converts that to usable JavaScript object using array=JSON.parse(result), where result is the result from PHP.

PHP's $array['me']='you' would then be array['me'] in JavaScript.

ajax return the whole output of the page so you can't return two strings with it but you can break that string into two

for example output of the page is : HelloWorld

now you want both Hello and World separate so make this output like : Hello,World OR Hello-World OR Hello|World

and split it with that delimiter

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