ajax请求成功,但php没有运行

Jor*_*dan 0 javascript php ajax jquery phpbb

我有一个非常简单的jquery函数,它将一个Ajax调用发送到一个应该回显警报的php文件,但对于我的生活,它无法让它运行.现在,我只是想触发php运行.这是javascript:

function getObdDescription(){

    var $code = document.getElementById("vehicle_obd_code").value;
    var $length = $code.length;


    if($length == 5){
        window.confirm($length);

        $.ajax({ url: '/new.php',
            data: {action: 'test'},
            type: 'post',
            success:function(result)//we got the response
            {
            alert('Successfully called');
            },
            error:function(exception){alert('Exception:'+exception);}
        });
        }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

这是new.php

<?php
    echo '<script language="javascript">';
    echo 'alert("message successfully sent")';
    echo '</script>';
?>
Run Code Online (Sandbox Code Playgroud)

我正在Chrome中测试,并且有网络选项卡,并且可以看到调用成功,同时,我收到弹出的"Successfully called"消息,因此jquery正在运行,并且Ajax调用成功.我也知道这url: '/new.php是正确的,因为当我从服务器上删除new.php时,我从控制台和网络选项卡中获得状态"404(Not Found)".我甚至没有条件地测试,但if($length ==...仍然没有运气.当然,我知道这不是问题,因为我得到了"成功调用"的回复.有任何想法吗?

Muh*_*lam 9

如果你需要alert文本,这不是它的工作方式,你应该在你的ajax success函数的前端做,按照KISS(保持简单愚蠢)php刚刚回显文本.这是正确的方法.

你应该做这个:

function getObdDescription(){

        var $code = document.getElementById("vehicle_obd_code").value;
        var $length = $code.length;


        if($length == 5){
            window.confirm($length);

            $.ajax({ url: '/new.php',
                data: {action: 'test'},
                type: 'post',
                success:function(result)//we got the response
                {
               alert(result);
                },
                error:function(exception){alert('Exception:'+exception);}
            });
            }
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

在你的PHP

<?php
   echo 'message successfully sent';
?>
Run Code Online (Sandbox Code Playgroud)