简体   繁体   中英

How to apply a condition in php on big ajax response?

I am doing ajax code, and I want the response to put sometimes in one div and other times in an other div on different responses, if I have a simple response like,

if(xhr.responseText='green'){
  //div1 sould change
}elseif(xhr.responseText='red'){
  //div2 sould change
}

but if I am getting a whole div with many elements form php page in responsetext so how I can apply a condition on that?

You can use

if(xhr.responseText.indexOf("green") != -1){ 
/*do something*/
}

to check if the whole div contains word green or not you can add unique identified to each different result.

Usually you would send JSON from your php code, including a variable to store the text and another that defines what div you should put data into. Something like

$object->divname = "div1";
$object->divcontents = ...;
//serialize and send json to the page.

In javascript you would deserialize json, decide what div to use and change its contents accordingly. How depends on frameworks you use.

You still can test responseText if you send entire contents of div in plain. But you would change the condition depending on what you need to do. For instance, if you need to choose div1 if the response contains red , use responseText.indexOf("red") != -1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM