Ajax 从 php 获取返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15126600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:37:06  来源:igfitidea点击:

Ajax get a return value from php?

phpjavascriptjqueryajax

提问by user1854438

I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?

我想提醒 php 方法的返回值,但没有任何反应。这里是ajax和php方法。谁能看到我做错了什么?

--------------------------------------… Ajax script

--------------------------------------... Ajax 脚本

$.ajax({
    type: 'get',
    url: '/donation/junk/4',
    data: datastring,
    success: function(data) {
        alert(data');
    }
});

--------------------------------------… php method

-------------------------------... php 方法

function junk($id)
{
    return "works11";
}

回答by Kristian

in PHP, you can't simply return your value and have it show up in the ajax response. you need to printor echoyour final values. (there are other ways too, but that's getting off topic).

在 PHP 中,您不能简单地返回您的值并将其显示在 ajax 响应中。您需要printecho您的最终值。(也有其他方法,但这已经离题了)。

also, you have a trailing apostrophe in your alert()call that will cause an error and should be removed.

此外,您的alert()调用中有一个尾随撇号,这会导致错误,应该将其删除。

Fixed:

固定的:

$.ajax({
    type: 'get',
    url: '/donation/junk/4',
    data: datastring,
    success: function(data) {
        alert(data);
    }
});

PHP:

PHP:

function junk($id)
{
    print "works11";
}

回答by zgr024

You have an extra ' in there on the alert(data') line

您在警报(数据)行上有一个额外的 '

This should work

这应该工作

$.ajax({
    type: 'get',
    url: '/donation/junk/4',
    data: datastring,
    success: function(data) {
        alert(data);
    }
});

And your PHP code should call the method also and echo the value

并且您的 PHP 代码也应该调用该方法并回显该值

function junk($id) {
    return 'works11';
}
exit(junk(4));

All you're doing currently is creating the method

您当前所做的就是创建方法

回答by Peter

ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.

ajax 返回文本,它不通过方法与 php 通信。它请求一个 php 页面,而 ajax 请求的返回是我们宝贝在浏览器中打开时会显示的任何内容。