簡體   English   中英

如何使用ajax將php的值傳遞給javascript

[英]How to pass the value of php to javascript using ajax

我有一個數組,必須使用ajax從后端傳遞到前端,我是ajax的新手,我知道語法,但被卡住了,下面是我的代碼

后端(PHP)

$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
                            $s_res = mysql_query($s_q, $db2);
                            while($row=  mysql_fetch_array($s_res))
                            {
                            echo $row['ans'];  
                            } 

$ result = array('ans'=> $ row ['ans']);

JavaScript代碼

function get_solution()
    {

        $.ajax({
            url: 'waiting.php',
            dataType: 'json',
            type: 'GET',
            timeout: 30 * 1000,
            data: {sol:row},
            success: function(json){   
                $('#saved').html(json.ans);

            },
            error: function(){}

        });

    }

我在以下代碼數據中收到錯誤:{sol:row}。

來自php的響應數據不是json格式。

$result = array('ans' => $row['ans'] );
echo json_encode($result);

將此添加到您的php代碼中

在PHP端創建一個JSON並使用$ .getJSON jquery捕獲它

服務器端:

$row_1 = array();
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$result = mysql_query($s_q) or die (mysql_error());

while($r = mysql_fetch_assoc($result)) {
    $row_1[] = $r;
}

$post_data = json_encode(array('ans' => $row_1));

echo $post_data;

客戶端:

  $.getJSON("result.php", function(json) {
            console.log(json)
     $.each( json, function( key, data ) {
           //loop through the json if necessary
     });
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM