Я использую этот 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>
Это то, что я получаю в моем поле ввода, когда я выбираю Product1 с $ («вход всего #») вал (ответ).
[{ "цена": "5", "время": "5"}]
Когда я изменить эту строку:.
$ ("вход всего #") вал (ответ);
с
$ ("# вход всего") Val (datashow.price).
У меня ничего не получается.
Мой php, кажется, правильно отображает мой json. Это просто выглядит так, что мой ответ не анализируется или не может быть каким-либо образом сохранен в var.
Вы пробовали какие-либо вычисления с помощью Ajax или jQuery? –
Да Я добавил код и объяснил проблему – Ame
Вы должны разобрать свой результат с помощью jQuery.parseJSON (response); e. var data = jQuery.parseJSON (ответ); $ ("ввод # итого"). Val (данные.цена); –