如何使用ajax和php异步获取数据

时间:2016-01-23 13:12:20

标签: php jquery ajax

我是ajax的新手。我想将输入内输入的文本显示到另一个div元素。这是下面给出的图像:

enter image description here

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>

    <label for="bar">Enter Text</label>
    <input id="bar" name="bar" type="text" value="" />   


<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>

<script >
 /* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "testajax.php",
        type: "post",
        async:true,
        data: values ,
        success: function (response) {                     

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });
</script>

</body>
</html>

这是php代码:

<?php
  $bar = $_POST['bar']
?>

请帮我解决问题&amp;如果可能的话,也尽量减少代码。谢谢

2 个答案:

答案 0 :(得分:2)

客户端

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>    
</head>
<body>
<form>
    <label for="bar">Enter Text</label>
    <input id="bar" name="bar" type="text" value="" />   
    <input type="submit" value="Go">
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<!-- For testing purposes comes here the JSON object (stringified) -->
<div id="jsonstring" style="font-family:monospace;">Json object</div>

<script type="text/javascript">
var values = $("form").serialize();

$("form").on("submit", function( event ) {
    event.preventDefault();
    var values = $( this ).serialize();

    $.ajax({
        url: "testajax.php",
        type: "post",
        async: true,
        data: values,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        success: function(json) {
            $('#result').html((json.content) ? (json.content) : '???');
            $('#result').prop('title', json.title);
            $('#jsonstring').html('Json object: '+JSON.stringify(json));
        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });

});

</script>

</body>
</html>    

服务器侧

<?php
    $bar = (isset($_POST['bar'])) ? $_POST['bar'] : '';
    $result = array(
        'title' => 'This is the result from an AJAX call',
        'content' => 'This is the result: <span style="color:red;">' . $bar . '</span>',
    );
    echo json_encode($result);
?>

答案 1 :(得分:2)

'MI*SS*IS*SI*PP*I'