2016-03-06 2 views
1

Я использую этот 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.

+0

Вы пробовали какие-либо вычисления с помощью Ajax или jQuery? –

+0

Да Я добавил код и объяснил проблему – Ame

+0

Вы должны разобрать свой результат с помощью jQuery.parseJSON (response); e. var data = jQuery.parseJSON (ответ); $ ("ввод # итого"). Val (данные.цена); –

ответ

1

Анализировать вам ответ, используя 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> 

Надеется, что это будет решить вашу проблему

////////////// ///////// Пробовал со статическим ответом ///////////

<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() { 
      var response = [{"price":"5","time":"5"}]; 
      $("input#total").val(response[0].price); 
     }); 
    </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> 

И я получаю правильный результат.

+0

нет, он все еще не показывает результат :( – Ame

+0

var data = jQuery.parseJSON (response); Console this data variable и показать мне результат консоли –

+0

Uncaught ReferenceError: ответ не определен (...) – Ame

0

использование JSON.parse();

success: function(response) { 
      var datashow = JSON.parse(response); 
      $("input#total").val(datashow.price); 
      } 

Это должно работать, если вы передаете JSON от сервера. И с вашим текущим кодом.

Если вы хотите, чтобы json автоматически анализировался, когда вы получаете его в функции успеха, используйте настройку dataType: "json". Таким образом, ваш код должен выглядеть следующим образом.

$.ajax({ 
     url: "ajax.php", // path to myphp file which returns the price 
     method: "post", // POST request 
     dataType: "json", // <--- setting dataType 
     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.price); // The response would be already parsed 
     } 
    }); 

Сообщите мне, если это поможет.

+0

Unfortunatelly no, делая предупреждение (datashow.price) сразу после того, как JSON.parse (response) показывает undefined. Это очень странно ... – Ame

+0

Можете ли вы показать, каково ваше значение ответа? Также возвращается ли ваш серверный код обратно? –

+0

Большое спасибо Узайр !!! – Ame

Смежные вопросы