使用ajax从文本框中的php变量中获取特定值

时间:2015-07-19 01:07:41

标签: javascript php jquery ajax

PHP CODE(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>

OUTPUT(所有文本框中的ID为“结果”

10
7.77
20
15.54
30
23.32

但我希望获得输出:
文本框ID“结果”中的echo $data["data"][0][recharge_amount]
文本框ID“result1”中的echo $data["data"][1][recharge_amount]
文本框ID“result2”中的echo $data["data"][2][recharge_amount]

依旧......

1 个答案:

答案 0 :(得分:1)

我希望我没有错误输入任何内容。

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 =&#34;结果&#34;到id =&#34; result0&#34;为了方便。

编辑:实际上我的php的一部分是多余的,所以我改变了它。