gpt4 book ai didi

javascript - 从 jQuery ajax 获取 php 数据,无需 html 表单

转载 作者:行者123 更新时间:2023-11-27 23:38:25 25 4
gpt4 key购买 nike

我的想法是使用 jQuery 编写单页 Web 应用程序并在 php 中使用服务器端,我想在不使用 html 表单的情况下完成它。到目前为止我有这个新的.php 文件:

<?php
echo "Welcome";
?>

和 JavaScript:

$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost/pmfServer/new.php',

success: function (data) {
alert('success' + data);
},
error: function(jqXHR,error, errorThrown) {

alert("Something went wrong " + errorThrown);

}
});
});

我收到的警报只是“成功”,没有其他任何内容。我正在运行 apache Web 服务器,当我在 Web 浏览器中输入相同的 url 时,它会显示“欢迎”。

由于我不打算使用表单,这是执行服务器端的正确方法吗?我必须使用一些框架吗?

最佳答案

试试这个:

$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost/pmfServer/new.php'
}).done(function(response){
var response = $.trim(response);
alert(response);
});
});

如果您仍然没有收到 ajax 的回复,请验证您的路径 (url: '....')

另请检查您的控制台是否有任何错误...

最后一件事:Ajax 文件不应该总是可以直接从浏览器访问...您可能需要考虑保护它们(尽管它们仍然可以通过 xmlhttprequest 访问:

<?php

//protect the file from un-auth access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}

echo "Welcome";

?>

当然,在您特定的“欢迎”情况下,这可能没有必要......我只是指更“敏感”的ajax文件;)

关于javascript - 从 jQuery ajax 获取 php 数据,无需 html 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33923260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com