2014-02-15 36 views
1

我已經形式,它看起來像:無法崗位後設置形式的屬性值是

<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

嘗試'$( 'postFrom。')ATTR( 「數據ID」,數據); 1',使用$阿賈克斯({}); –

+0

或返回的數據是Json數組! –

回答

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 
      }); 
}); 
+0

偉大的..它的作品...! – Chinmoy

+0

@ user3172721很高興爲您提供幫助。 –

0

this在ajax處理程序裏面沒有引用提交的表單,你可以使用如下所示的關閉變量如$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 
    }); 
}); 

jQuery.ajax()

的所有回調在此引用是在設置傳遞到$就上下文 選擇對象;如果未指定上下文,則這是對Ajax設置本身的引用。