使用AJAX时显示警报

时间:2016-07-08 12:45:59

标签: javascript php jquery html ajax

我是两个文件,一个PHP文件和另一个由javascript和HTML组成的文件。

PHP文件:

<?php
session_start(); //start session

$_SESSION['data'] = "The content should be displayed as alert in the JS file";

JS / HTML文件:

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<form class="form-item" id="idForm">
        <input type="hidden" name="product_code" value="prince"/>
        <button id="btn_add" type="submit">Add to Cart</button>
</form>
<script>


    $(function(){
        $("#idForm").submit(function(e) {

            var url = "test2.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $("#idForm").serialize(),
                success: function()
                {
                    alert(/*The content of the session in the php file should be display here*/); // show response from the php script.
                }
            });

            e.preventDefault();
        });
    });
</script>

在PHP文件中,我有一个会话$_SESSION['data']。我想做的就是能够在alert()

之后making the ajax request to test2.php显示该会话的内容

2 个答案:

答案 0 :(得分:4)

将响应添加为成功的参数。响应基本上是浏览器中通常显示的任何内容(包括语法错误)

  $.ajax({
            type: "POST",
            url: url,
            data: $("#idForm").serialize(),
            success: function(resp)
            {
                alert(resp); // show response from the php script.
            }
        });

确保回显您希望在PHP脚本中显示的内容。任何被回应的东西都将在AJAX响应中返回:

<?php
session_start(); //start session

$_SESSION['data'] = "The content should be displayed as alert in the JS file";
echo $_SESSION['data'];

答案 1 :(得分:2)

1.在php你必须写到最后: -

echo $_SESSION['data']; // so that it will go as a response to the ajax call

2.然后在ajax: -

success: function(response){ // grab the response
   alert(response); // alert the response
}