Jer*_*lle 22 javascript php ajax jquery
我遇到了一个问题我提交了一个包含小数据的简单表单,当我在console
选项卡中检查时,ajax的URL似乎正在工作但是在处理完ajax之后它将发出错误警告并将其重定向到我的主页并从控制台选项卡我有这个weird error
:
未捕获的异常:内存不足
在我的ajax中,我只有这个简单的代码:
$("#add-comment").on('click', function() {
var id = $('input[name=\'review_id\']').val();
var customer_id = $('input[name=\'customer_id\']').val();
var $comment = $('textarea[name=\'user_comment\']').val();
var sample = "test";
$.ajax({
url: 'index.php?route=product/product/writeSubComment',
type: 'post',
dataType: 'json',
data: { text: sample },
beforeSend: function() {
},
success: function(data) {
console.log(data.test);
},
error: function() {
alert('ERROR!!!');
}
});
});
Run Code Online (Sandbox Code Playgroud)
在我的PHP控制器中,我有这个功能
public function writeSubComment() {
$json = array();
$json['test'] = $this->request->post['text'];
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Run Code Online (Sandbox Code Playgroud)
Dra*_*kes 41
从您重定向到主页的描述,但在ajax响应部分中没有代码来执行此操作,我怀疑元素#add-comment是表单中的提交按钮.
如果是这种情况,那么当您单击#add-comment提交按钮时,您的表单可能会在运行ajax代码的同时提交.这将解释内存不足错误,因为在页面重定向时ajax javascript被清除.
您需要阻止表单提交,并让success()或failure部分处理下一步(即刷新页面,更新注释框).一种方法是改变
$("#add-comment").on('click', function() {
...
Run Code Online (Sandbox Code Playgroud)
至
$('#add-comment').on('click', function(event){
event.preventDefault();
...
Run Code Online (Sandbox Code Playgroud)
或者更改提交按钮
<button type="submit" ...>Add comment</button>
Run Code Online (Sandbox Code Playgroud)
至
<button type="button" ...>Add comment</button>
Run Code Online (Sandbox Code Playgroud)
或者像这样更改表单标签
<form onsubmit="return false;">
Run Code Online (Sandbox Code Playgroud)
这是我可以获得的最佳猜测.
小智 5
我在Firefox中测试时遇到了类似的问题.更改按钮的type
距离submit
来button
为我工作.
<button type="submit" ...>Add comment</button>
Run Code Online (Sandbox Code Playgroud)
至
<button type="button" ...>Add comment</button>
Run Code Online (Sandbox Code Playgroud)