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 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决