【发布时间】:2014-07-20 18:27:18
【问题描述】:
我意识到这可能是重复的,但我已经看了 2 个小时,找不到我做错了什么,查看其他帖子也没有显示我的错误。
我在处理 CodeIgniter 下的 AJAX 调用中返回的 JSON 时遇到了挑战。我是 AJAX 的新手,我正在从我读过的东西和其他自学中调整它。除了在 div 中显示结果消息之外,一切都运行良好,我的页面正在刷新并以原始文本显示 JSON。
function makeAjaxCall(){
$.ajax({
url: "http://localhost/testing/index.php/urlsaving/jquery_save",
cache: false,
data: $('#frm').serialize(),
dataType : 'json',
type: "post",
success: function( data ){
$('#validation-error').html(data.msg);
//have tried 'return false;' here to halt the default action
}
});
}
这是发送请求的表单,也是我希望显示返回数据的表单:
<!DOCTYPE html>
<html>
<head>
<title>URL saving sandbox</title>
</head>
<body>
<div id="adding_urls">
<form action="http://localhost/testing/index.php/urlsaving/jquery_save" method="post" accept-charset="utf-8" id="frm">
<div id="validation-error"></div> < -- div where I want feed back posted
<h2>Enter Web Address:</h2>
<input type="text" name="url" value="" size="75" /> <br>
<div><input type="submit" onclick="javascript:makeAjaxCall();" id="submit_frm" value="Submit" /></div>
</form>
</div><!-- /adding_urls -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>
<script type="text/javascript" src="http://localhost/testing/js/another_method.js"></script>
</body>
</html>
【问题讨论】:
-
实际上,不需要使用表单元素进行 ajax 调用。您可以删除表单标签并通过一个简单的按钮更改提交,该按钮必须调用您的 ajax 函数。您的问题是您正在提交表单,而您不会这样做
-
@kmsdev - 另一方面,删除表单标签意味着你不能只做
$(form).serialize(),你必须自己解析表单,这就是为什么表单是个好主意, 但是提交事件应该被捕获,因为提交表单的方法有很多,并且只听一个按钮的点击通常是一个坏主意。 -
@adeneo 我认为在这种情况下你是完全正确的
标签: jquery ajax codeigniter