我有表格,看起来像:
<form method="POST" action="create.php" data-id="0" class="postForm">
<input type="hidden" id="#formId" value="1">
<textarea class="formBodyText"></textarea>
<button type="submit">Post</button>
</form>
此表单的ajax调用如下:
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
$.post("create.php",{'formId':$("#formId").val(),'formBodyText':$(this).find('.formBodyText').val()},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
$(this).attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
问题在于$(this).attr("data-id",data);
,它没有为表单设置新值。
这段代码有什么问题?
答案 0 :(得分:0)
this
没有引用提交的表单,你可以使用像$form
这样的闭包变量来解决这个问题。
$(document).on("submit", ".postFrom", function (event) {
event.preventDefault();
var $form = $(this);
$.post("create.php", {
'formId': $("#formId").val(),
'formBodyText': $(this).find('.formBodyText').val()
}, function (data) {
console.log("Return : " + data); //working fine , I mean getting expected result
$form.attr("data-id", data); // want to set the return data as form data-id attribute value
});
});
所有回调中的this引用是上下文中的对象 选项在设置中传递给$ .ajax;如果未指定上下文, 这是对Ajax设置本身的引用。
答案 1 :(得分:0)
尝试,
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
var cache = $(this); // get the form object here and use that inside of $.post
$.post("create.php",
{'formId':$("#formId").val(),
'formBodyText':$(this).find('.formBodyText').val()
},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
cache.attr("data-id",data); // want to set the return data as form data-id attribute value
});
});