当我点击提交按钮时,我无法收到值yearend
。相反,我得到了一个未定义的值。单击“提交”按钮后,如何获得yearend
值?
我的代码:
$("#company").change(function() {
$("#dFrom").val("");
$("#dTo").val("");
var pass_code = $("#company").val();
var callpage = "dentrycomp.php?pass_code=" + pass_code
var yearend= null;
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
}
});
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert(yearend +"company");
this alert box getting the right value yearend.i want that value recieve in under submit button
return true;
});
$('#submit').live('click',function() {
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button"+yearend);
答案 0 :(得分:2)
var yearend = null;
$("#company").change(function() {
$("#dFrom").val("");
$("#dTo").val("");
var pass_code = $("#company").val();
var callpage = "dentrycomp.php?pass_code=" + pass_code
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend = data,
$("#content").html("")
$("#content").html(data)
}
});
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert(yearend + "company");
this alert box getting the right value yearend.i want that value recieve in under submit button
return true;
});
$('#submit').live('click', function() {
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button" + yearend); });
您应该全局声明yearend
,即代码顶部。
答案 1 :(得分:1)
我认为这是因为范围不同。您必须在请求之前定义变量,然后重新定义它并在AJAX请求之后获取它。
答案 2 :(得分:1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
$('#submit').live('click',function(){
alert("this is submit button"+yearend);
});
}
});
});
</script>
</head>
<body>
</body>
</html>
答案 3 :(得分:0)
您在ajax电话yearned
之外的ajax的预期行为是undefined
。将您的点击功能放在ajax调用中。因此,一旦您的ajax调用完成并成功,您将在成功函数中附加您的事件侦听器。请改用此逻辑:
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
$('#submit').live('click',function(){
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button"+yearend);
});
}
});