dourao1968
dourao1968
2015-07-19 01:07

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

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 CODE(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(all in textbox having id "result")

10
7.77
20
15.54
30
23.32

but i want to get output :
echo $data["data"][0][recharge_amount] in textbox id "result"
echo $data["data"][1][recharge_amount] in textbox id "result1"
echo $data["data"][2][recharge_amount] in textbox id "result2"

and so on....

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongmo9996 dongmo9996 6年前

    I hope I have not mistyped anything.

    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>
    

    btw. I have changed id="result" to id="result0" for ease.

    EDIT: actually a part of my php was redundant, so I changed it.

    点赞 评论 复制链接分享

相关推荐