PHP 代码(plan-api.php)
$requestUrl = "url.com";
$response = (file_get_contents($requestUrl, false, $context));
$data = (json_decode($response, true));
echo $data["data"][0][recharge_amount];
echo "<br>";
echo $data["data"][0][recharge_talktime];
echo "<br>";
echo $data["data"][1][recharge_amount];
echo "<br>";
echo $data["data"][1][recharge_talktime];
echo "<br>";
echo $data["data"][2][recharge_amount];
echo "<br>";
echo $data["data"][2][recharge_talktime];
echo "<br>";
HTML/AJAX 代码(plan-ajax.php)
Please enter a Mobile number
<input type="text" id="search">
<br>
<input type="text" id="result">
<input type="text" id="result1">
<input type="text" id="result2">
<input type="text" id="result3">
<script>
$(document).ready(function() {
$('#search').keypress(function(){
$.ajax({
type: "GET",
url: "plan-api.php",
data: 'result=' + $('#search').val(),
success: function(output){
$('#result').val(output);
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
输出(所有内容都在 ID 为“结果”的文本框中)
10
7.77
20
15.54
30
23.32
但我想获得输出:
在文本框 id“result”中回显 $data["data"][0][recharge_amount]
在文本框 id“result1”中回显 $data["data"][1][recharge_amount]
在文本框 ID“result2”中回显 $data["data"][2][recharge_amount]
等等......
最佳答案
我希望我没有输入任何错误。
PHP:
<?php
/*
* We assume your data has this structure, for example:
*
$data['data'][0]['recharge_amount'] = 10;
$data['data'][0]['recharge_talktime'] = 5;
$data['data'][1]['recharge_amount'] = 11;
and so on
*/
// we output the data as JSON
echo json_encode($data);
?>
HTML/JS
Please enter a Mobile number
<input type="text" id="search">
<br>
<input type="text" id="result0">
<input type="text" id="result1">
<input type="text" id="result2">
<input type="text" id="result3">
<script>
$(document).ready(function() {
$('#search').keypress(function(){
$.ajax({
type: "GET",
url: "plan-api.php",
data: 'result=' + $('#search').val(),
dataType: "json",
success: function(responseText){
$.each(responseText.data, function(key,value){
$('#result'+key).val(value.recharge_amount);
});
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
顺便说一句。为了方便起见,我已将 id="result"更改为 id="result0"。
编辑:实际上我的 php 的一部分是多余的,所以我更改了它。
关于javascript - 使用ajax从文本框中的php变量获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497050/