[英]Pass PHP value to javascript using 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);
?>
您返回的數據在response
參數中。 您必須在PHP中echo
數據才能獲得結果
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);
您沒有在PHP腳本中回顯任何內容。
嘗試將您的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)。
我看到很多事情需要糾正
ajax中的數據以這種方式執行data: {'codigo':textVal},
因為您使用的是$ _GET ['codigo'],這會導致第二次更正,因此您使用了type:"POST"
因此還必須訪問$ _POST變量而不是$ _GET變量,最后ajax的目標不顯示/返回任何您echo
或echo json_encode()
內容
最好的解決方案是使用echo json_encode(“您要使用的陣列/值”);
然后將javascript代碼中的JSON解析為obj = JSON.parse(response);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.