通过按钮单击将输入值传递给脚本中的php函数

时间:2019-10-01 00:27:16

标签: javascript php jquery

我需要使用输入字段中的值-无需POST-从外部源进行查找。

输入字段具有与之关联的按钮,该按钮在按下按钮时调用脚本。因此,我需要将输入字段(id ='lookup')放入函数的参数中(该函数在脚本中调用)。

这是脚本中的代码行,需要输入字段(称为“ 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;
}

2 个答案:

答案 0 :(得分:0)

由于您已经了解PHP是服务器,而JS是客户端,因此不能直接在PHP中使用JS变量。

有两种方法。

    您已经说过不想使用的
  1. $ _ POST。我认为不使用$ _POST的原因是浏览器提示继续刷新页面。

  2. 使用$ _GET将在您的网址中添加一个参数。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="get">
<p>Part Number = <input type="text" id="lookup" name="lookup" value= "12345"></p>
<button>Get product name for this part number</button>
</form>

另外,在文件的开头添加这一行作为PHP变量来访问。

$lookup = $_GET["lookup"]; 

答案 1 :(得分:0)

可以使用ajax。

尝试

创建文件:api_request.php

<?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;
}
$number = $_GET["part"];
$product_name = api_request($number);
echo json_encode(array( "product_name" => $product_name ));

并以此修改javascript

$(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
    $.get(`api_request.php?part=${ lookup.value }`,(resp)=>{
$('#product_name').text(resp.product_name); // display it on the screen in that 
},"json");

});

});