想要在使用 laravel(或常规 PHP)成功时将字符串从 PHP 返回给 AJAX


Want to return a string from PHP to AJAX on success using laravel (or regular PHP)

如何从PHP文档返回一个字符串,然后做一些if(string == 'test')我应该分配数据类型吗?我应该使用回波还是回显?这是我目前拥有的。

阿贾克斯代码:

$.ajax({
                type: 'get',
                url: 'phonegap',
                data: senddata,
                success: function(response) {
                    var a = $(this).html(response);
                    if(a == 'Success')
                        alert("YAY");
                    else
                        alert("NAY");
                },

PHP代码/拉拉维尔

if (Auth::attempt($userdata)) {
                $user = Auth::user();
                //return $user->utid;
                return "Success";
            }
            else {
                return "Error";
            }

在 ajax 调用中添加此选项:

dataType: 'json',

在 php 中,您可以将所需的所有数据放入一个数组中,然后简单地打印出该数组的 json:

echo json_encode($results);

当你这样做时,javascript 中的响应对象将包含你所有的数组数据。

例如,如果你定义像 $results = array('success' => true); 这样的数组,在 javascript 中你可以检查 response.success 是真还是假。您可以通过这种方式传递多个值。

试试这个:

$.ajax({
    type: 'get',
    url: 'phonegap',
    datatype: 'json',
    data: senddata,
    success: function(response) {
        if (response.success)
            alert("YAY");
        else
            alert("NAY");
    }
});

而在PHP中

if (Auth::attempt($userdata)) {
    $user = Auth::user();
    $result = array('success' => false, 'userid' => $user->utid);
}
else {
    $result = array('success' => false);
}
echo json_encode($result);

你试过回声吗?我相信它一定有效

这样做:

if (Auth::attempt($userdata)) {
  $user = Auth::user();
  // return $user->utid;
  echo "Success";
  exit;
} else {
  echo "Error";
  exit;
}

几个关键的事情:

- success回调中的$(this)不引用原始元素

-使用echo返回响应

您可以通过以下方式将上下文变量设置为当前元素:

var that = $(this)
$.ajax({
    ...
    success: function(response) {
        var a = that.html(response);
        if(a == 'Success')
            alert("YAY");
        else
            alert("NAY");
    },
});

只需从服务器echo响应即可。