【发布时间】:2019-10-01 00:27:16
【问题描述】:
我需要使用输入字段中的值 - 没有 POST - 从外部源进行查找。
输入字段有一个与之关联的按钮,它在按钮按下时调用脚本。所以我需要将输入字段(id = 'lookup')放入函数的参数中(该函数在脚本中被调用)。
这是脚本中需要输入字段(称为“查找”的输入字段)中的值的代码行
<?php $product_name = api_request(lookup);?>
我的代码如下。
(注意:我知道'PHP是服务器端,JS是客户端'。但是按钮点击确实调用PHP函数,并且代码确实显示函数的返回值如果你可以这样做:
<?php $product_name = api_request('1234');?>
这将通过我的api_request() 函数返回“我的产品名称”。)
在api_request()的参数中放入脚本变量需要什么?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p>Part Number = <input type="text" id="lookup" value= "12345"></p>
<button>Get product name for this part number</button>
<div id='product_name'>Product Name Goes Here </div>
<script>
$(document).ready(function(){
$("button").click(function(){
// returns value of input field
var lookup = document.getElementById('lookup');
// need to put the input field 'lookup' into the function's parameter
<?php $product_name = api_request(lookup);?>
var product_name = "<?php echo $product_name; ?>";
$('#product_name').text(product_name); // display it on the screen in that div ID
});
});
</script>
</body>
</html>
<?php
function api_request($partnumber) {
// code that returns the product name for that part number, hard coded here
$product_name = "My Product Name";
return $product_name;
}
【问题讨论】:
-
当你在调用中加入一个常量时,例如
api_request('1234')在页面加载时可以(并且是)评估该值。单击按钮时不会对其进行评估。查看您的页面源代码,您将在文本中看到var product_name = <some constant value>。您只能在页面加载后通过 ajax 调用等访问 PHP 函数。
标签: javascript php jquery