duanpo2813 2016-07-08 12:45
浏览 294
已采纳

使用AJAX时显示警告[重复]

This question already has an answer here:

I am two files, a PHP file and another file made of javascript and HTML.

PHP file :

<?php
session_start(); //start session

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

JS/HTML File:

<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>

In the PHP file, I have a session $_SESSION['data']. All I want to do, it is to be able display the content of that session in alert() after making the ajax request to test2.php

</div>
  • 写回答

2条回答 默认 最新

  • dongquanyu5816 2016-07-08 12:47
    关注

    Add response as parameter to success. Response is basically anything that would normally display in the browser (including syntax errors)

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

    Make sure to echo what you wish to display in your PHP script. Anything which gets echoed will be returned in the AJAX response:

    <?php
    session_start(); //start session
    
    $_SESSION['data'] = "The content should be displayed as alert in the JS file";
    echo $_SESSION['data'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳