我如何在php codeigniter上运行ajax
我正在尝试在我的codeIgniter项目上使用javascript代码。 但我没有执行它。 我尝试了太多方法来解决它:我调用外部js代码,它没有用。 我把它放在我的视图页面中也不行。 我认为这个问题很简单,但我看不出来。 你怎么看待这个问题?
view.php
New Customer function makeAjaxCall(){ $.ajax({ alert("I'm here"); // I cant see that type: "post", url: "http://localhost/codeigniter_2/index.php/homepage/verifyUser", cache: false, data: $('#addCust').serialize(), success: function(json){ try{ var obj = jQuery.parseJSON(json); alert( obj['STATUS']); }catch(e) { alert('Exception while request..'); } }, error: function(){ alert('Error while request..'); } }); } Customer Add
list
conroller.php
public function verifyUser() { $userName = $_POST['customerID']; $phone = $_POST['phone']; $address = $_POST['address']; if($userName=='' && $phone=11){ $status = array("STATUS"=>"true"); } echo json_encode ($status) ; }
怎么了??
您需要将代码放在文档就绪处理程序中 –
$(document).ready(function() { // your code here function makeAjaxCall.... // EDIT: adding the click handler $('#formSubmit').click(function().... });
而且,而不是这样做 –
我会给输入一个id –
并向JavaScript添加单击处理程序 –
$('#formSumbit').click(function(e) { e.preventDefault(); // keeps the button from acting normally makeAjaxCall(); // calls the function });
还有一件事 – 在代码中使用console.log()
而不是alert()
。 警报不是一种好的故障排除方法,因为它们会导致代码暂停,直到确认并在AJAX调用期间使用它们特别糟糕。
改变这一点
至
EDITED
$userName = $_POST['customerID'];// check this $phone = $_POST['phone']; $address = $_POST['address']; if($userName=='' && $phone=11){ $status = array("STATUS"=>"true"); } echo json_encode ($status) ;
还要在表单中添加id
您好在这里,您可以查看以下链接,它对您有用
http://www.ccode4u.com/how-jquery-ajax-works-in-codeigniter.html
谢谢 :)