1.經(jīng)常用form表單提交的小伙伴有沒有發(fā)現(xiàn),form表單默認(rèn)的提交是沒有返回值的谅年,而且默認(rèn)提交成功之后是跳轉(zhuǎn)稼病,跳轉(zhuǎn)的action的路徑,下面寫一下默認(rèn)的提交如何獲取到form表單的返回值json良蛮,并且阻止默認(rèn)的跳轉(zhuǎn)動作抽碌。
頁面結(jié)構(gòu)見下面:
<form target="form" action="" enctype="multipart/form-data" method="post">
? ? ?<input type="file">
? ? ?<button type="submit" ? ?id="submit" style="display:none">提交</button>?
</form>
<iframe name="form" id="form" style="display:none"></iframe>
//細(xì)心的小伙伴有沒有發(fā)現(xiàn)上面的結(jié)構(gòu)多了一個iframe的隱藏內(nèi)聯(lián)框架,其實(shí)最主要的就是我們的form表單的target屬性值等于這個iframe的name和id决瞳,那么我們就可以用iframe來接收返回值货徙,并且把默認(rèn)的跳轉(zhuǎn)讓iframe去跳轉(zhuǎn),下面是js的代碼皮胡,來獲取這個返回值json痴颊。
$("#submit").click();
$("#form").load(function(){
? ? ? var text = $(this).contents().find("body").text(); ? ? ?//獲取到的是json的字符串
? ? ?var j = $.parseJSON(text); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //json字符串轉(zhuǎn)換成json對象
? ? ?console.log(j)
})
//注意,只要這個iframe框架加載完成就說明發(fā)送成功了屡贺。