简体   繁体   English

将数据从PHP脚本发送到jQuery Ajax请求

[英]Send data from PHP script to jQuery Ajax request

I'm new to web development, so please pardon any silly mistakes! 我是Web开发的新手,所以请原谅任何愚蠢的错误!

I'm using the following code send a jQuery Ajax request: 我正在使用以下代码发送jQuery Ajax请求:

var d = "email=" + email + "&password=" + password;

        $.ajax({
            url: 'login/c_login_form.php',
            data: d,
            dataType: "text", //expected type from server
            type: "POST",
            success: function(str, status) {
                        console.log(str + ": " + status);
                     },
            error: function(obj) {
                        alert("Fatal error. Failed to send Ajax request.");
                     }
        });

For simplicity, let us assume that login/c_login_form.php is currently blank (but has the php tags, of course) and is to return a set data every time. 为简单起见,让我们假设login/c_login_form.php当前为空(但是当然具有php标记),并且每次都会返回一组数据。

I was under the impression that whatever I echo from the server will be passed to the success function, but it's not working that way. 我给人的印象是,我从服务器发出的任何echo都将传递给success函数,但这种方式无法正常工作。 What is the way to send data from PHP script back to Ajax? 将数据从PHP脚本发送回Ajax的方式是什么? Although I've used text datatype, I'd be happy if somebody can tell me how to return JS objects. 尽管我使用了文本数据类型,但是如果有人可以告诉我如何返回JS对象,我会很高兴。

To summarize comments in a concrete answer: 总结评论中的具体答案:

<?php
    header('Content-Type: application/json');

    $data = array("status" => 1, "err" => "example_error_code");
    echo json_encode($data);
?>

Please note, as Anthony Grist suggests, that you need, on your Javascript: 请注意,正如Anthony Grist所建议的那样,您需要在Javascript上:

dataType: "json"

instead of: 代替:

dataType: "text"

See also jQuery ajax docs : 另请参阅jQuery ajax docs

...
dataType (default: Intelligent Guess (xml, json, script, or html))
...

You can refer this answer for Ajax post request. 您可以将这个答案用于Ajax发布请求。

To send back data from PHP file to JS you need to use echo . 要将数据从PHP文件发送回JS,您需要使用echo

If you are passing more than one variable then you can use echo json_encode($array_of _variables); 如果要传递多个变量,则可以使用echo json_encode($array_of _variables); . If there is only one variable than please you can use just echo $variable . 如果只有一个变量,请只使用echo $variable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM