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

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?