2016-08-19 55 views
0

喜歡我在數據庫如何將此值傳遞給JavaScript並在HTML頁面上一一顯示?

enter image description here

100個值我想這個值通過PHP使用AJAX傳遞給JavaScript。

PHP CODE:

for($i=0;$i<=9;$i++) 

{ 

$random = (10 * $i) + rand(1,10); 

$result = mysql_query("SELECT * FROM check_val WHERE id = '$random'") or exit(mysql_error()); 

if(mysql_num_rows($result) == 1){ 

$row = mysql_fetch_assoc($result); 
$value = $row['val'];  
$alpha = $row['alp']; 

} 

$arr = array("val"=>$value, 
     "alp"=>$alpha 
     ); 

echo json_encode($arr)."<br>"; 

} 

OUTPUT:

{"val":"1","alp":"A1"}<br> 
{"val":"15","alp":"A15"}<br> 
{"val":"23","alp":"A23"}<br> 
{"val":"37","alp":"A37"}<br> 
{"val":"42","alp":"A42"}<br> 
{"val":"51","alp":"A51"}<br> 
{"val":"67","alp":"A67"}<br> 
{"val":"71","alp":"A71"}<br> 
{"val":"84","alp":"A84"}<br> 
{"val":"100","alp":"A100"}<br> 

AJAX代碼:

$.ajax({ 
url: "index.php", 
type: "post", 
dataType: "json", 

success: function(response) { 

    $("#val").html(response.val); 
    $("#alp").html(response.alp); 

    } 
}); 

這AJAX代碼用於當O本安輸出是這樣的:

{"val":"1","alp":"A1"} 

即只是一個單一的價值

我如何可以讀取所有的值,並點擊在HTML頁面的按鈕時1顯示出來1。

HTML代碼:

<p id="val"></p><br> 
<p id="alp"></p><br> 
<button>Click Me</button> 
+0

因此,第一次點擊按鈕「{」val「:」1「,」alp「:」A1「}'出現。第二次點擊時,出現「{」val「:」15「,」alp「:」A15「}」等等? – Jamy

+0

是的@JamyGolden請幫忙...從這幾天卡住 – Ankit

回答

0

試試這個: 後端:

$offset = (int) $_POST['offset']; 
if ($offset < 0) { 
    $offset = 0; 
} 
$result = array(); 
$resource = mysql_query("SELECT * FROM check_val ORDER BY id LIMIT 1 OFFSET {$offset}"); 
if ($resource === false) 
{ 
    exit(mysql_error()); 
} elseif (mysql_num_rows($resource)) { 
    $result = mysql_fetch_assoc($resource); 
} 
echo json_encode($result); 

前端的html:

<div class="wrapper"> 
    <p id="val"></p><br> 
    <p id="alp"></p><br> 
</div> 
<button>Click Me</button> 

前端的javascript:

$("button").on("click", function() { 
    var $container = $(".wrapper"); 
    var offset = parseInt($container.data("offset"), 10) || 0; 

    $.ajax({ 
     url: "index.php", 
     type: "post", 
     dataType: "json", 
     data: {offset: offset}, 
     success: function(response) { 
      if (response != undefined && response.val != undefined) { 
       $("#val").html(response.val); 
       $("#alp").html(response.alp); 
       $container.data("offset", offset+1); 
      } 
     } 
    }); 
}); 
+0

請注意,mysql_ *函數已棄用。使用mysqli或PDO –

0

我不是100%確定如果這是您正在尋找的答案,但我會嘗試。我也不太清楚你如何使用ajax。

echo "<script>var jsonContent = ["; 

for($i=0;$i<=9;$i++) { 
    ... 

    echo json_encode($arr) . "," 
    ... 
} 

echo "]</script>"; 

然後JavaScript的(jQuery的)::

var clickCount = 0; 

$('button').on('click', function() { 
    $("#val").html(jsonContent[clickCount].val); 
    $("#alp").html(jsonContent[clickCount].alp); 

    clickCount++; 
}); 

每次按鈕被點擊時,內容

如下我想創建從PHP腳本元件和JavaScript JSON可變應該開始循環瀏覽jsonContent數組中的內容。

相關問題