简体   繁体   English

将PHP的对象数组导入Javascript

[英]Import PHP's array of objects into Javascript

I have a php script which constructs an array of objects based on HTML input and then displays the results. 我有一个php脚本,它根据HTML输入构造一个对象数组,然后显示结果。 What I am trying to do is to display the results page by page. 我想要做的是逐页显示结果。 Just like Google (or other search engines) display their results. 就像谷歌(或其他搜索引擎)展示他们的结果一样。 When the user clicks next, the succeeding chunk of results is echoed back to the page. 当用户单击下一步时,后续的结果块将回显到页面。

Doing that with Javascript (a Javascript function is called as onClick event), I have to import the whole array prepared by the PHP script and index it accordingly. 使用Javascript(一个Javascript函数被称为onClick事件),我必须导入由PHP脚本准备的整个数组并相应地索引它。 Here is part of the script so you know the kind of array 这是脚本的一部分,因此您知道数组的类型

foreach($results as $id => $currentResult)
{
    $temp[$i]->id = $id;
    $page = get_page_by_id($id);
    $temp[$i]->url = $page['url'];
    $temp[$i]->title = $page['title'];
    $temp[$i]->score = $currentResult->score;
    ++$i;
}
$temp = qsort($temp);

So $temp is the array I am going to use in Javascript. 所以$ temp是我将在Javascript中使用的数组。 This can totally be eliminated by using PHP only but I'm trying to take the load off the server. 这可以通过仅使用PHP完全消除,但我正试图从服务器上卸载。

you can use json_encode to send that array to javascript, and eval it there so that you get you data structure back. 您可以使用json_encode将该数组发送到javascript,并在那里评估它,以便您获得数据结构。

http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-encode.php

To pass value from PHP to js, use in your HTML template something like: 要将值从PHP传递给js,请在HTML模板中使用以下内容:

<script type="text/javascript">
    var my_array = <?php echo json_encode($my_array_to_path); ?>;
</script>

Then in your JS you can use next syntax: 然后在你的JS中你可以使用下一个语法:

my_array['some_key']; // or my_array.some_key

Great stuff, I think. 我认为很棒的东西。

i would recommend using ajax $('#my_link_id').onClick(function() { //do ajax stuff, load from server }); 我建议使用ajax $('#my_link_id')。onClick(function(){//执行ajax的东西,从服务器加载});

see http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/

In PHP do this: 在PHP中执行此操作:

    $temp = qsort($temp);
    json_encode( $temp );

in HTML You can use jQuery to load the data back in: 在HTML中您可以使用jQuery将数据加载回:

    $.ajax( {
      url: 'some_page.php',
      dataType: 'json',
      success: function( data ) {
          var returnObj = $.parseJSON( data );
          // and more code goes here
      }
    } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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