有没有可能有人可以告诉我这段代码有什么问题?
我在一个页面上有 4 或 5 个链接,它们使用 ajax_load 函数加载。当我在它们之间单击时,这一直有效。我在 ajax_load 函数中有 2 个 console.log 警报,当点击链接时,它总是显示在 Google Chrome 中。
当我单击“提交”按钮时,问题就开始了,该按钮调用了我的 form_submit 函数。它总是有效 - 我在控制台日志中收到一条成功的消息 - 但是当我返回链接时,大多数时候只出现第一条控制台日志消息。(在处理“form_submit”之前,出现了 2 条消息。)
它不会:
if (current_url_method != url + method) {
console.log('You got to the url + method part. But sometimes I dont get this far.');
current_url_method = url + method;
无论如何,如果有人能告诉我出了什么问题,我将不胜感激。这里是:
$(document).on("ready", function(){
//I want to load content into the '.page-content' class, with ajax
console.log('load ajax when document starts. This always works.');
var ajax_loaded = (function(response) {
$(".page-content")
.html($(response).filter(".page-content"));
$(".page-content .ajax").on("click",ajax_load);
});
//use the ajax function below for submitting forms
var form_submit = (function(e) {
console.log('form_submit is working. This always works.');
e.preventDefault();
var url = $(this).attr("action");
var method = $(this).attr("method");
var data = {}
$(this).find("input, textarea, select").each(function(i){
var name = $(this).attr("name");
var value = $(this).val();
data[name] =value;
});
$.ajax({
"url": url,
"type": method,
"data": data,
"success": ajax_loaded,
"error": function () {alert("bad");}
});
});
//the function below is called by links that are described
//with the class 'ajax', or are in the div 'menu'
var history = [];
var current_url_method;
var ajax_load = (function(e) {
console.log('load ajax on clicks. This always works.');
e.preventDefault();
history.push(this);
var url =$(this).attr("href");
var method = $(this).attr("data-method");
if (current_url_method != url + method) {
console.log('You got to the url + method part. But sometimes I dont get this far.');
current_url_method = url + method;
$.ajax({
url: url,
type: method,
async: false,
success: ajax_loaded
});
}
});
//monitor for clicks from menu div, or with
//the ajax class, or the 'submit button'.
//why the trigger?
$("#menu a").on("click",ajax_load);
$(".ajax").on("click",ajax_load);
$("#menu a.main").trigger("click");
$(".search-box form").on("submit", form_submit);
});