我正在使用這個js從我的數據庫MYSQL恢復一些數據,它工作得很好。獲取解析爲輸入字段的json值
<script type = "text/javascript" >
$(document).ready(function() { // When the document is ready
$("select#product1").on("change", function() { // We attach the event onchange to the select element
var id = this.value; // retrive the product id
$.ajax({
url: "ajax.php", // path to myphp file which returns the price
method: "post", // POST request
data: "id=" + id, // I retrieve this data in my$_POST variable in ajax.php : $_POST[id]
success: function(response) { // The function to execute if the request is a -success-, response will be the price
$("input#total").val(response); // Fill the price
}
});
});
}); </script>
以我輸入#總我得到這個值(例如):
[{ 「價格」: 「5」, 「時間」: 「10」}]
如何能我只得到價格價值或時間價值? 我搜索了一些json解析器,但我無法將它放入我的輸入中。
這是我完整的HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="j_idt2">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select#product1").on("change", function() {
var id = this.value;
$.ajax({
url: "ajax.php",
method: "post",
data: "id=" + id,
success: function(response) {
var datashow = jQuery.parseJSON(response);
$("input#total").val(response);
}
});
});
});
</script>
</head>
<body>
<select id="product1" name="product1">
<option value="" selected="selected">-</option>
<option value='17'>Product1</option>
</select>
<input id="total" type="text" name="total" class="form-control" />
</body>
</html>
這是我進入我的輸入字段時,我選擇與產品1 $(「#輸入總」)VAL(響應)。
[{ 「價格」: 「5」, 「時間」: 「5」}]
當我改變這一行:
$( 「輸入#總」)VAL(響應);
與
$( 「輸入#總」)VAL(datashow.price)。
我什麼都沒有得到。
我的PHP似乎渲染正確我的JSON。它看起來像我的迴應沒有被解析或不能以任何方式存儲到一個變種。您使用響應jQuery.parseJson 如更改下面
<script type = "text/javascript" >
$(document).ready(function() { // When the document is ready
$("select#product1").on("change", function() { // We attach the event onchange to the select element
var id = this.value; // retrive the product id
$.ajax({
url: "ajax.php", // path to myphp file which returns the price
method: "post", // POST request
data: "id=" + id, // I retrieve this data in my$_POST variable in ajax.php : $_POST[id]
success: function(response) { // The function to execute if the request is a -success-, response will be the price
var datashow = JSON.parse(response);
$("input#total").val(datashow[0].price);
}
});
});
}); </script>
希望這樣你的代碼
您是否嘗試過使用Ajax或jQuery進行任何計算? –
是的,我添加了代碼和問題的解釋 – Ame
你應該用jQuery.parseJSON(響應)解析你的結果; 例如var data = jQuery.parseJSON(response); $(「input#total」)。val(data。價錢); –