George_Fal 2016-11-16 20:14 采纳率: 0%
浏览 15

jQuery Ajax-错误的响应

I have a problem with jQuery ajax function:

var arrayIdEq = JSON.stringify(iditem);
    $.ajax({
        type: "POST",   
        url: "index.php",
        dataType : 'text', 
        contentType: 'application/json; charset=utf-8',
        data: {
            arrayIdEq : arrayIdEq
        },
        success: function(answer) {
            alert(answer);
        },
        complete: function() {
        },
        error: function(jqXHR, errorText, errorThrown) {
            alert(jqXHR+" - "+errorText+" - "+errorThrown);
        }
    });

"arrayIdEq" contains number from 0 to 7, or string "EMPTY". PHP code:

elseif(isset($_POST['arrayIdEq'])){ 
$answer = "my_answer";
return $answer;

After request, when success response come, alert show up... but here's the problem. Instead of "$answer" value, alert contains... HTML code from my main page!

<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
</head>
<body>
<h1>Medivia</h1>
    <form action="index.php" method="POST">
    <label>E-mail:<br><input type="text" name="mail" required></label>
    <br>
    <label>Hasło:<br><input type="password" name="pass" required></label>
    <br>
    <button name="login">Zaloguj się</button>
</form>
</body>
</html>

I have no idea what happend here. Could anybody explain to me what happend there? What did i do wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33749131 2016-11-16 20:20
    关注

    Your answer variable in the success function will contain the complete output of your php script.

    So when you call index.php and you do:

    elseif(isset($_POST['arrayIdEq'])){ 
      $answer = "my_answer";
      return $answer;
    }
    

    The script will only exit if the return statement is called from the main script (not from within a function) but the output will be the output generated by the script until that point.

    Your script should output - and not return - only what you want returned to the javascript.

    Probably a separate script for ajax requests will be a more convenient solution than using the index.php file you use to build the complete page.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料