2012-08-30 160 views
0

我有一個提供數據庫值的php代碼。我需要JavaScript變量中的這些值。使用Ajax將PHP值傳遞給javascript

JavaScript代碼

<script src="http://code.jquery.com/jquery-1.8.0.js"></script> 
<script type="text/javascript"> 
    function text() { 
     var textVal=$("#busqueda_de_producto").val(); 
     $.ajax(
     { 
      type:"POST", 
      url:"index.php", //here goes your php script file where you want to pass value 
      data: textVal, 
      success:function(response) 
      { 
       // JAVSCRIPT VARIABLE = varable from PHP file. 
      } 
     }); 

     return false; 
    } 
</script> 

PHP文件代碼:

<?php 
    $q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo']; 
    $res11 = mysql_query($q11); 
    $row11 = mysql_fetch_array($res11); 
?> 
+0

http://whathaveyoutried.com/ –

+1

在你的PHP代碼,只是做'回聲json_encode($ row11);' –

+0

如果你只是想將變量從一個php頁面傳遞給另一個,只需使用SESSION。你只是從一個腳本變量,並傳回給index.php在你的HTML/JavaScript頁面中它們有什麼用處? – Champ

回答

3

你返回數據是在response參數。你必須在echo PHP您的數據得到的結果

1

使用JSON格式是因爲它的鍵值性質的方便

。使用將PHP數組轉換爲JSON。

echo的json_encoded變量

,你將能夠通過$.ajax

+0

但結果是NULL –

0

你是不是在呼應你的PHP腳本什麼接收JSON響應數據。

試着改變你的PHP這樣的:

<?php 
     $q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo']; 
     $res11 = mysql_query($q11); 
     $row11 = mysql_fetch_array($res11); 

     echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want. 
?> 

然後在你的Ajax調用,您可以在您的成功處理程序中編寫alert(response)提醒這一點。

提示

發送數據到服務器的URL序列化字符串:request=foo&bar=4。如果你喜歡它,你也可以試試JSON。

不要使用mysql_* PHP函數,因爲它們已被棄用。試用PHP數據對象(PDO)的search

0

我看到很多的東西,需要加以糾正

,因爲使用了$ _GET在阿賈克斯的數據做這種方式data: {'codigo':textVal}, [「codigo」],這導致了第二修正,您使用type:"POST"所以你也必須訪問$ _ POST變量,而不是$ _GET變量,最後你的AJAX不顯示的目標/返回任何東西,你要麼echo,或echo json_encode()

0

最好的解決方案是使用 回聲json_encode( 「你的陣容/價值將被使用」);

然後在javascript代碼中解析JSON爲 obj = JSON。解析(響應);

1

javascipt的/ HTML:

<script src="http://code.jquery.com/jquery-1.8.0.js"></script> 
<script type="text/javascript"> 
    function text() 
    { 
     var textVal=$("#busqueda_de_producto").val(); 
     $.post('index.php', { codigo:textVal }, function(response) { 
      $('#output').html(response.FIELDNAME); 
     }, 'json'); 

     return false; 
    } 
</script> 
<span id="output"></span> 

PHP:

$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'"; 
$res11 = mysql_query($q11); 
$row11 = mysql_fetch_array($res11); 

echo json_encode($row11);