[英]AJAX call doesn't work after submitting a form
This is my code at www.domain-a.de/external.search.js. 这是我在www.domain-a.de/external.search.js上的代码。 I call it from www.domain-b.de/test.php:
我从www.domain-b.de/test.php调用它:
(function ($) { // make the ajax request $.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) { // append the form to the container $('#embedded_search').append(data); $('#embedded_search form').attr('action',''); myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?' var frm = $('#embedded_search form'); // click on submit button frm.submit(function (ev) { $.getJSON( myUrl ) .done(function( json ) { console.log( "JSON Data: " + json ); }) .fail(function( jqxhr, textStatus, error ) { var err = textStatus + ", " + error; console.log( "Request Failed: " + err ); }); }); }); })(jQuery);
After running this code I don't get any message in console. 运行此代码后,我在控制台中未收到任何消息。 What is wrong with that code?
该代码有什么问题?
frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.
Your code is not calling the submit
handler on the item, it is simply binding it. 您的代码没有在项目上调用
submit
处理程序,只是在绑定它。 You should do the frm.submit(function
binding outside of your $.getJSON
callback; then inside the callback add 您应该在
$.getJSON
回调外部进行frm.submit(function
绑定;然后在回调内部进行添加
frm.submit()
Which triggers the event. 触发事件。
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload. 同样,当提交发生时,您的操作将发生,但是表单将照常提交到后端,从而导致页面重新加载。
After the line 下线后
frm.submit(function (ev) {
Add 加
ev.preventDefault();
So your overall code should be 所以你的整体代码应该是
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.