Javascript 使用jquery ajax访问php脚本返回的JSON

Javascript 使用jquery ajax访问php脚本返回的JSON,javascript,php,jquery,json,ajax,Javascript,Php,Jquery,Json,Ajax,基本上,我的程序是一个网页,有5个单选按钮可供选择。我希望我的web应用程序能够在每次选择不同按钮时更改按钮下方的图片 我的问题是,在从访问mysql中数据的php scrip收到JSON后,JSON解码阶段出现了 以下是我的ajax.js文件的代码: $('#selection').change(function() { var selected_value = $("input[name='kobegreat']:checked").val(); $.ajax( {

基本上,我的程序是一个网页,有5个单选按钮可供选择。我希望我的web应用程序能够在每次选择不同按钮时更改按钮下方的图片

我的问题是,在从访问mysql中数据的php scrip收到JSON后,JSON解码阶段出现了

以下是我的ajax.js文件的代码:

$('#selection').change(function() {
   var selected_value = $("input[name='kobegreat']:checked").val();

   $.ajax( {
       url: "kobegreat.php",
       data: {"name": selected_value},
       type: "GET",
       dataType: "json",

       success: function(json) {
           var $imgEl = $("img");
           if( $imgEl.length === 0) {
               $imgEl = $(document.createElement("img"));
               $imgEl.insertAfter('h3');
               $imgEl.attr("width", "300px");
               $imgEl.attr("alt", "kobepic");
           }
           var link = json.link + ".jpg";
           $imgEl.attr('src', link);
           alert("AJAX was a success");
      },
      cache: false
  });
});
和我的php文件:

<?php


   $db_user = 'test';
   $db_pass = 'test1';       

   if($_SERVER['REQUEST_METHOD'] == "GET") {
       $value = filter_input(INPUT_GET, "name");
   }

   try {
       $conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
       $conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
       $stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
       do_search($stmt, $value);
  } catch (PDOException $e) {
      echo 'ERROR', $e->getMessage();
  }

  function do_search ($stmt, $name) {
      $stmt->execute(['name'=>$name]);

      if($row = $stmt->fetch()) {
          $return = $row;
          echo json_encode($return);
      } else {
          echo '<p>No match found</p>;
      }
  }

?>

每当我现在运行web应用程序时,页面上的其余图像都会消失,而我试图显示的图像也不会显示。我得到的警告是AJAX取得了成功,但是除了警告之外,没有任何其他结果。我不知道我在这方面哪里出了问题,任何帮助都会很棒

如前所述,您应该使用JSON.parsejson;解析JSON响应

此外,您还应该使用更简单的设置专门针对div元素:
$target.append

您需要解析JSON变量jsonObj=JSON.parsejson;一般不建议混合你的回答。您应该在所有情况下都回显JSON,因为AJAX需要它。您能确认从服务器得到了什么吗?也许是一些UTF8有趣的事情,JSON是空的。
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
   <input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
   <input type="radio" name="kobegreat" value="kobe2"/>Kobe2
   <input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>

<div id="target">
    <h3>Great Kobe Moment!</h3>
</div>
greatshots(name, link)

name         link
------       --------
kobe1        images/kobe1
kobe2        images/kobe2
kobe3        images/kobe3