2014-10-31 64 views
0

我想创建一个网站,将大量使用ajax(jQuery)。为此,我想使用外部$ .ajax函数并在需要时传递参数。我想要一个完整的例子来指导我。我在服务器端使用php,返回的数据将是json。我在服务器端没有问题,但无法获得任何ajax的工作。请在示例方面提供任何帮助,我们将非常感谢。

我我所做的第一个示例是为以下

<!DOCTYPE html> 
<html> 
<head> 
<meta charset = "utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

<script> 


$(document).ready(function(){ 

     $("#find").click(function(){ 

      $.ajax({ 
       // the URL for the request 
       url: "findPatient.php", 
       // the data to send (will be converted to a query string) 
       data: {pnhsno: $('#search').val()}, 
       // whether this is a POST or GET request 
       type: "GET", 
       // the type of data we expect back 
       dataType : "json", 


       // code to run if the request succeeds; 
       // the response is passed to the function 
       success: function(json){ 

        $("#ex1").val(json[0].firstname); 

       } 


      }); 


     }); 
}); 

</script> 


<link rel = "stylesheet" type ="text/css" href = "pascss/patient.css " > 
</head> 
<body> 

<div id="wrapper"> 

<form class="form-patient" "> 
<fieldset> 
<legend>Patient Details</legend> 
<label for="ex1">First name</label> 
<input type="text" name="ex1" id="ex1" /> 
</fieldset> 
</form> 

<form class="form-wrapper"> 
<fieldset> 
<legend>Find Patient</legend> 
    <input type="text" id="search" placeholder="Enter patient NHS number" required> 
    <input type="submit" value="Find" id="find" onclick ="> 


    </fieldset> 
</form> 



</div> 

</body> 
</html> 

即使这个例子并不完全工作。它似乎是它正在得到正确的json返回 并显示它在文本框中一个毫秒之前完成document.ready功能完成。当它完成擦除附加在文本框上的文本。我只是无法理解它。可以请某人为我解释它。非常感谢

回答

1

提交表单会加载一个新页面并清除现有页面。

如果JavaScript成功,则阻止默认窗体操作。

// Capture the event object 
...click(function(event){ 

然后,在结束:

event.preventDefault();