开发者

Ajax / jQuery to PHP and back again?

开发者 https://www.devze.com 2023-02-28 22:15 出处:网络
I have an ajax call made with jQuery, something like this: $.ajax({ type: \"POST\", url: ajaxurl, data: data,

I have an ajax call made with jQuery, something like this:

$.ajax({
    type: "POST",
    url: ajaxurl,
    data: data,
    success: function(response){
        alert(response);
    }
});

I get data from PHP like this:

$data_array = get_data();
foreach($data_array as $data)
{
    echo $data;
}

PHP to slow

The PHP data function call is slow because it gets very much data from the database, might fetch images, make some json calls and other slow things.

One loop round at the time

Therefor I need to get the PHP code just do one round, then Javascript and then do the next round in the loop.

More than one way to solve it?

There might be more than one way to do it. Which one is prefer开发者_运维问答ed? Javascript foreach-loop, JSON and global Javascript variables comes to mind.


You can set the return type in your ajax function as xml or json, and then return you array in either of these types. I feel that JSON js the preferred one for your solution.


I'm slightly against storing actual images in the database. I prefer to only keep a unique link for them and then return that instead of the actual image. This would speed the query up a fair bit. I agree with mad_programmer that the JSON js would be preferred for your situation.


You could manipulate your query to do a limit. So something like:

 var total_count = ajax_get_sql('select statement with count');
 var curr_count = 0;
 var set_number = 10; 
 var select_statement_without_limit = 'statement';  

 setTimeout('fetch_data()',0);

 ...

 function fetch_data()
 {
      if(curr_count < total_count)
      {
           ajax_get_sql(select_statement_without_limit with limit appended);
           curr_count = curr_count + set_number;
           setTimeout('fetch_data()',0);
      }
 }

With all your ajax calls set to wait for a response instead of continuing. I would keep the sql logic in PHP, but use javascript to query the server many times. This will prevent your JS script from giving long execution errors. I haven't really taken into account data manipulation, but you can probably figure it out!

0

精彩评论

暂无评论...
验证码 换一张
取 消