简体   繁体   English

Ajax将内容从json数组加载到div中

[英]Ajax load content into div from a json array

My webpage is supposed to generating a series of questions in a random order. 我的网页应该会随机产生一系列问题。 Each question is a seperate HTML page with a picture and multiple options.On page load, there should a default question and thereafter on clicking next a new page is loaded. 每个问题都是一个单独的HTML页面,其中包含图片和多个选项。在页面加载时,应该有一个默认问题,然后单击下一步将加载新页面。 I am currently: 我目前:

  1. Creating a php array with the names of the html pages and shuffling it. 用html页面的名称创建一个php数组并将其改组。
  2. Converting this array into a json array to be accessed in Javascript. 将此数组转换为要用Javascript访问的json数组。
  3. Trying to ajax load the page. 尝试ajax加载页面。

I am stuck at the third step; 我陷入了第三步。 how do you send a json array element in an ajax call ie 你如何在ajax调用中发送一个json数组元素

$.ajax({
  url: name+".html",
  success: function(html){
    $("#container").empty().append(html);
  }
});

where name is the name of the webpage stored in the json array and container is the div on my current php page. 其中name是存储在json数组中的网页的名称,容器是我当前的php页面上的div。 In case there is an easier way of doing the above task, I am open to that too. 如果有一种更简单的方法来完成上述任务,我也愿意这样做。

Thanks! 谢谢!

EDIT Step 2: 编辑步骤2:

         var xdata = <?php echo json_encode($testArray); ?>;

where $testArray is the php shuffled array of webpages. 其中$ testArray是php随机排列的网页数组。

$.ajax({ url: name+".html", success: function(html)     
                $("#container").empty().append(html);                           
                }                                      
                });

there are 1 '{' and 2 '}' try 尝试1个'{'和2个'}'

$.ajax({ url: name+".html", success: function(html){     
                $("#container").empty().append(html);                           
                }                                      
                });

Use the jQuery load function . 使用jQuery load函数

var pageToLoadIntoContainer = 'Test1.html';

$('#container').load( pageToLoadIntoContainer );

Extending this answer to try and solve all of your elements... 扩展此答案以尝试解决您的所有元素...

<?php

$pageArray = shuffle(array(
  'Test1' ,
  'Test2' ,
  'Test3'
));

....

?>
<script>

var pageArray = <?php echo json_encode( $pageArray ); ?>;

....

$('#container1').load( pageArray[0] );
$('#container2').load( pageArray[1] );
$('#container3').load( pageArray[2] );

</script>

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

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