[英]Return a value from php to $.get
Now I am upgrading my website user experience, so I'm trying modify my form from form action
to ajax
.现在我正在升级我的网站用户体验,所以我正在尝试将我的表单从
form action
修改为ajax
。 Coding now work fine, server side can update the database, but I don't know how to return the custom message to my user.编码现在工作正常,服务器端可以更新数据库,但我不知道如何将自定义消息返回给我的用户。
My html coding.我的 html 编码。
<form method="post" id="jnfarm_pop">
blablabla...
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login();">submit</button>
</form>
My php file plugin.php
我的 php 文件
plugin.php
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
My jQuery
我的
jQuery
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
Now the alert
doesn't work, I am also try like现在
alert
不起作用,我也在尝试
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
result = JSON.parse(result); alert(result.final); //not working also
}
and和
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result = JSON.parse(result)) => {
alert(result.final); //this show alert unidentified
}
Can someone correct my coding?有人可以纠正我的编码吗?
Change改变
return json_encode(['final' => $final]);
to至
echo json_encode(['final' => $final]);
return
is really only useful when you're inside a PHP function.仅当您在 PHP function 中时,
return
才真正有用。 If you want to output something back to the caller of the script then you need to use echo
, as always.如果您想将 output 的内容返回给脚本的调用者,那么您需要像往常一样使用
echo
。
To make your example work do the following:要使您的示例正常工作,请执行以下操作:
change your PHP code from将您的 PHP 代码从
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
to:至:
<?php
//coding.....
$final = 'custom wording';
echo json_encode(['final' => $final]);
?>
and your jQuery code from this:以及您的 jQuery 代码:
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
to this:对此:
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert(result);
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
PHP can return something to an ajax call by either printing or echoing. PHP 可以通过打印或回显将某些内容返回给 ajax 调用。 And ajax can't use variables you defined in PHP.
并且 ajax 不能使用您在 PHP 中定义的变量。 The echo'ed value in your PHP script will be the result value in your ajax call.
PHP 脚本中的回显值将是 ajax 调用中的结果值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.