各位晚上好,
我目前正在尝试清理我的内联 JS 并将其分解为自己的 .js 文件,并将我的一些代码分解为函数。下面我提供了我的代码,我有一个div
名为#main
. 在准备好文档时,我想调用我的firstLoad
函数。它只是调用$("#main").load("login.php");
似乎很简单,但是我的下一步是在提交表单时,我想序列化提交的数据,转为字符串并通过 post 提交。如果我将表单硬编码到index.php
文件中,出于某种原因,这将起作用,但如果我使用 .load 填写 .load 则不会#main
。我不知道为什么会这样,我相信如果有人能解释一下这很简单,那就太好了。我的代码如下:
更新 经过更多搜索,我遇到了这个线程,上面写着以下内容:
事实证明,jquery .load() 函数工作完美,我正在接近这个错误。
一旦 .load() 函数成功完成,它就会调用程序员包含的任何“回调”函数,就像任何其他接受回调作为其“参数”之一的 jquery 函数一样。一旦 .load() 函数出错或成功开始 HTML 替换和加载新内容,它就完成了, 但就是这样!然后,无论加载内容需要多长时间,但您的 .load 调用在此之前已经完成。因此,期望回调在 .load 内容加载后运行只会让您失望。;)
我希望其他人可以像我一样从中吸取教训,包括那些认为我认为是这样的人。证明:如 jquery ajax .load 页面中所述,回调在请求完成时执行,而不是在加载完成时执行。尤里卡。哎呀。
这导致了后续问题,在加载内容添加到 DOM 后如何操作表单?这肯定是一个简单的修复,但我是 AJAX 的新手,可以在正确的方向使用微调。我注意到在 login.php 脚本中添加一个文档(就绪)可以正常工作,因为它是与 html 一起添加的,但它似乎不是最干净的做事方式,因为我试图阻止内联 JS。还有什么建议吗?
/更新
PHP/HTML
索引.php
<?php
session_start();
$sessionNumber = session_id();
?>
<!doctype html>
<!-- Conditional comment for mobile ie7 blogs.msdn.com/b/iemobile/ -->
<!--[if IEMobile 7 ]> <html class="no-js iem7" lang="en"> <![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>MyMobile</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/h/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/m/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" href="img/l/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="img/l/apple-touch-icon.png">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body>
<div id="container">
<header id="header">
<img alt="Logo" src="img/logo.png" />
<div id="blackHead">Please sign-in to continue</div>
</header>
<div id="main" role="main">
</div>
<footer id="footer">
<div id="greyFoot">
© 2012 ACME<br />
<pre id="result"></pre>
</div>
</footer>
</div> <!--! end of #container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/firstLoad.js"></script>
</body>
</html>
登录.php
<?php session_start();
$sessionNumber = session_id();
?>
<!-- begin login form -->
<?php if(isset($_SESSION['sessionemail'])){ ?>
<a href="logout.php" id="logout">Logout</a>
<?php }else { ?>
<form id="logForm" name="login" method="post" action="#">
<label for="sessionemail">Email</label><br />
<input id="sessionemail" type="email" name="sessionemail" autofocus="autofocus" autocapitalize="off" maxlength="150" required="true" value="" class="inputText" /><br />
<label for="password">Password</label>
<input id="password" type="password" name="password" required="true" value="" class="inputText" /><br />
<br />
<input type="hidden" name="sessionid" id="sessionid" value="<?php echo $sessionNumber; ?>" />
<input type="hidden" name="subtocall" id="subtocall" value="g2.web.login.sub" />
<input type="submit" value="Sign-In" name="submit" class="submitBox" />
</form><!-- end login form -->
<?php } ?>
最后,我的 JS/Jquery
firstLoad.js
//function serializes our object
(function($){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
//firstLoad function runs on document ready
//it loads the login form into the main div and slides
//the container down
(function($){
$.fn.firstLoad = function(){
return this.each(function() {
$("#container").slideUp("slow", function(){
$("#main").load('./login.php', function(){
$("#container").slideDown("slow", function(){
});
});
});
});
};
})(jQuery);
//logParse takes the loginResponse from the server
//changes from string to object, runs a check for authentication then
//manipulates the object dropping excess keys and adding new relevant ones for
//the intial to do list call
(function($){
$.fn.logParse = function(xml){
return this.each(function() {
//parse the JSON login check string from the XML response
var loginResponse = $(xml).find('string').text();
//setup isBad variable for error check
var isBad = false;
//convert to JSON object from parsed string data
loginResponse = $.parseJSON(loginResponse);
//check if the sessionID is correct and user authenticated properly
if((loginResponse.SESSIONID != "<?php echo $sessionNumber; ?>") || (loginResponse.ISAUTHENTICATED == 0)){isBad = true;}
//if error flag is raised alert and bounce back to login
if(isBad){
alert("Unauthorized connection, please try again.");
}
//if there are no errors
else{
alert("so far so good!");
//set up a new JSON object for to do list passback
//and import the values from the lognResponse object
//var todoPost =
}
});
};
})(jQuery);
$(document).ready(function(){
//hide screen for slidedown
//$("#container").addClass("noShow");
//allow cross domain scripts
$.support.cors = true;
//call firstLoad function to slide in the login prompt
$("#main").firstLoad(function(){
//create JSON object to store form input for AJAX POST
//create submit listener
$("#logForm").submit(function(){
alert("inside submit");
//parse form into formObj for data passing and manipulation
var formObj = JSON.stringify($("form").serializeObject());
//output initial formObj into result pane
$("#result").text(formObj);
$("#main").text("submitted: " + formObj);
//AJAX POST call
$.ajax({
//type of communication
type: "POST",
//action for form
url: "http://mydomain.com/JSONService.asmx/G2WebRequest",
//data to be passed
data: "request="+ formObj,
//type of data passed in
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//enable cross domain
crossDomain: "true",
//data type returned from webservice
dataType: "xml",
//if login POST was successful
success: function(xml){
alert("post successful");
$.logParse(xml);
},
//if login POST failed
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
});