简体   繁体   中英

How to interactively get data from php script using javascript

I have this php script:

<?php
$arr = array(array("a","b"),array("c","d"));
qq($arr);
function qq($arr){
foreach($arr as $ar => $r){
//getting some work done
//sending the array $r (or values)to javascript
}
}
?>

Is it possible to get the value of 0 array using javascript before array 1.

what i get so far is this js from stackoverflow:

<script type="text/javascript">
function q(){

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://127.0.0.0.1/q.php");
xmlhttp.send(null);
xmlhttp.onreadystatechange = callbackFunction;

function callbackFunction(){
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseText;
document.getElementById("q").value = xml;
}}}
</script>

but it's not doing what i want(i think i'm missing something).

my html:

<input type="submit" onclick="q();" />
<div id="q"></div>
<div id="q1"></div>

Is it possible to put array 0 value in div(id=q) and when array 1 is ready put it's value in div(id=q1)

The "normal" HTTP Requests via XMLHttpRequest() do not allow such behaviour in a single request.

You have the following options instead:

Server Send Events

upside

  • They are incredibly easy to build. Nothing really special is needed on the server. Just google for server sent events and you'll find some examples on how they work.
  • They go through proxys and firewalls just as well as any other http request, because it is a normal http request.

downside

  • Does not run on Internet Explorer (?)
  • May fail to update in realtime if a proxy somewhere buffers too much. However in this case it still works, it just misses the realtime communication

Websockets

upside

Works in all recent browsers. Enables you to do full duplex communication and gets everything right that you need.

downside

  • May or may not work through proxies depending on their configuration.
  • Special extensions are needed on the server

(Long-) polling

upside

  • Best compatibility (works even in older browsers, no issues with proxies or firewalls)

downside

  • Creates lots of overhead because it does create for each message a new http connection
  • You need to store intermediate results somewhere because the poll requests come in different threads to your application than your code generation mechanism.

can you try with

if (xmlhttp.readyState == 4){
  xml = xmlhttp.responseText;
  document.getElementById('q').innerHTML=xml;
}}}

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