dtueufe82643 2015-01-16 15:19
浏览 56
已采纳

jQuery $ .get()和$ .ajax()不从PHP获取数据

I have a script that is supposed to alert a message taken from a PHP file after a click event. I've tried both jQuery $.get() and $.ajax(), but both didn't worked. $.ajax() works but alerts an empty message, $.get() alerts "null".

load.php

<?php
    $string = "prova";
    echo json_encode($string);
?>

jquery_save.js

$(document).ready(function(){
    $("#carica").click(function(){
        loadPHP();
    });
});

function loadPHP() {
    $.get( "load.php", function( data ) {
        alert(data)
    }, "json" );
};

index.html

<!doctype html>
  <html>
    <head>
      <meta charset="utf-8">
      <title>This is just a test for Stackoverflow</title>
      <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script type="text/javascript" src="jquery_save.js"></script>
    </head>

  <body>
    <form>
      <input style="background-image:url(img/lc-load.png);" type="submit" value="Carica" name="carica" id="carica">
    </form>
  </body>
</html>

In this way I get the alert but with a "null" output. I've tried this too:

load.php

<?php
    $string = "prova";
    echo $string;
?>

jquery_save.js

$(document).ready(function(){
    $("#carica").click(function(){
        loadPHP();
    });
});

function loadPHP() {
    $.ajax({
        type: 'GET',
        url: 'load.php',
        success: function(data) {
            alert(data); 
        }
    });
};

This gives me an alert with noting inside. Both ways makes the page refresh after closing the alert message (and I don't want this happens). I used another function with $.ajax() to give variables to another PHP file without problem, but I'm not able to take variables from PHP files.

  • 写回答

2条回答 默认 最新

  • douzui0143 2015-01-16 15:22
    关注

    You have to prevent the default click action -

    $("#carica").click(function(event){
        event.preventDefault();
        loadPHP();
    });
    

    Your alert does not occur because of the page redirection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧