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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载