2017-03-20 4 views
1

main.htmlをの取得情報フォームのJSONエンコード

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <script src="jquery-3.1.1.min.js"></script> 
    <script src="jsfile.js"></script> 
    </head> 
    <body> 
      <button onclick="cart(0)"> hi </button> 
      <p id="disp"></p> 
    </body> 
    </html> 

jsfile.js

function cart(id1) 
{ 

    var id=id1; 
    //alert("enterd "+id); 
    document.getElementById("disp").innerHTML ="hi"; 
    if (window.jQuery) { 
    // jQuery is available. 

    // Print the jQuery version, e.g. "1.0.0": 
    //alert(window.jQuery.fn.jquery); 
} 
     $.ajax({ 
     url:"add.php ", 
     type:"POST", 

     data:{ 
      item_id: id, 
     }, 
     success:function(response) { 

     document.getElementById("disp").innerHTML =response.value1; 
     }, 
     error:function(){ 
     alert("error"); 
     } 

     }); 

} 

add.php

<?php 
    if(isset($_POST['item_id'])){ 
    //if(count($_POST)>0) 
     echo json_encode(array("value1" => "hello", "value2" => "hi")); 

    } 
?> 

午前コレクションI私はjson配列から情報を得ることができません。私はrespnse.value1によって情報を取得しようとしています。しかし、私は未定義の私を返します..何がエラーかもしれない?

答えて

0

JSONを使用する前に解析する必要があります。成功関数をこれに変更してください -

success:function(response) { 
    var res = JSON.parse(response); 
    document.getElementById("disp").innerHTML = res.value1; 
}, 
+0

ありがとうございました! –

関連する問題