我想从php文件获取表单输入值到javascript,如下所示: PHP文件:
<html>
<head>
<meta charset = "UTF-8">
<title> Search Customer by Field </title>
<script type="text/javascript" src="../lib/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../src/search-by-invoice-no.js"></script>
<table id="results" border="1"></table>
</head>
<body>
<?php
if( isset($_GET["invoiceNo"]) && "" != $_GET["invoiceNo"])
{
}
else
{
?>
<form id = "form1">
Invoice Number <input id="invoice" name="invoiceNo" type="text" value="<?=isset($_GET['invoiceNo'])? $_GET['invoiceNo'] :""?>">
<br/>
<input id="submit_btn" type="submit">
</form>
<?php
}
?>
</body>
</html>
JS档案:
$(document).ready(function() {
var invoiceNo = $('#invoice').val(); //Returns undefined
alert(invoiceNo);
//etc...
为什么会这样?我尝试了其他几种方法,但都失败了。
答案 0 :(得分:1)
您的if
/ else
结构毫无意义。如果$ _GET ['invoiceNo']存在且不为空,那么您执行if
逻辑,因此永远不会创建表单。但是,在您的表单中,您检查$ _GET ['invoiceNo']是否存在。它永远不会,除非它是空的,那么在那里使用它有什么意义呢?
答案 1 :(得分:-1)
你有几个错误:if if / else是你没有得到一个值的原因,除此之外你输入和输入元素内的php输出中缺少一个括号应以/&gt;
<html>
<head>
<meta charset = "UTF-8">
<title> Search Customer by Field </title>
<script type="text/javascript" src="../lib/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../src/search-by-invoice-no.js"></script>
</head>
<body>
<?php
if( isset($_GET["invoiceNo"]) && "" != $_GET["invoiceNo"])
{ ?>
<form id = "form1" action='mypage.php' method='GET'>
Invoice Number <input id="invoice" name="invoiceNo" type="text" value="<?php echo (isset($_GET['invoiceNo']))? $_GET['invoiceNo'] :""; ?>" />
<br/>
<input id="submit_btn" type="submit" />
</form>
<?php
}
else
{
?>
<p>No value received</p>
<input id="invoice" name="invoiceNo" type="hidden" value="0" />
<?php
}
?>
</body>
</html>
此外,您甚至不需要检查它是否已按照您的设置进行设置,例如
Invoice Number <input id="invoice" name="invoiceNo" type="text" value="<?php echo $_GET['invoiceNo']; ?>" />
也能正常工作
修改
<html>
<head>
<meta charset = "UTF-8">
<title> Search Customer by Field </title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function(){
var invoice = $('#invoice').val();
if(invoice == 0)
{
alert('No value was passed');
}
else
{
alert(invoice);
}
});
</script>
</head>
<body>
<?php
if( isset($_GET["invoiceNo"]) && "" != $_GET["invoiceNo"])
{ ?>
<form id = "form1" action='mypage.php' method='GET'>
Invoice Number <input id="invoice" name="invoiceNo" type="text" value="<?php echo $_GET['invoiceNo']; ?>" />
<br/>
<input id="submit_btn" type="submit" />
</form>
<?php
}
else
{
?>
<p>No value received</p>
<input id="invoice" name="invoiceNo" type="hidden" value="0" />
<?php
}
?>
</body>
</html>