[英]How to get an php echo with jquery
I know this question was asked many times before, I searched really long for the solution but I couldn'd find one, that's why I'm asking.我知道这个问题以前被问过很多次,我搜索了很长时间的解决方案,但我找不到一个,这就是我问的原因。 First: I'm trying to connect my HTML-File to my JavaScript file and that worked pretty well.
第一:我正在尝试将我的 HTML 文件连接到我的 JavaScript 文件,并且效果很好。 What I want to do now is to display data from my MySql-DB on my HTML-Site, that's why I'm using PHP.
我现在想要做的是在我的 HTML 站点上显示来自 MySql-DB 的数据,这就是我使用 PHP 的原因。 I wanted to start simple, that's why I tried to echo "Hello World".
我想从简单开始,这就是为什么我试图回应“Hello World”。 But when I run my site, I don't get only "Hello World", I'm getting the whole PHP-Code.
但是当我运行我的网站时,我得到的不仅仅是“Hello World”,而是整个 PHP 代码。 How can I fix that problem?
我该如何解决这个问题?
test.php测试文件
<?php
echo 'Hello World';
index.html索引.html
<!DOCTYPE html>
<html>
<head>
<title>MySite</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="size">
<button id="saveBtn" value="Click" type="button" >Save</button>
<script src='test.js'></script>
</body>
</html>
test.js测试.js
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var in= $('input#size').val();
if (size== '')
alert("Error");
else {
$.post("test.php", { input: size}, function (data, status) {
alert("data + " : " + status);
});
}
});
});
Everything is actually working fine, except you have some typos in your Javascript file:实际上一切正常,除了您的 Javascript 文件中有一些拼写错误:
$.post()
function is illegal. $.post()
函数的第二个参数是非法的。 It should look like this to work:它应该看起来像这样工作:
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var theInput = $('input#size').val();
if (size== '')
alert("Error");
else {
$.post("test.php", function (data, status) {
alert(data + ":" + status);
});
}
});
});
ALSO
还
It looks like you're trying to prevent the user from sending off the AJAX request until there is something in the input.看起来您试图阻止用户发送 AJAX 请求,直到输入中有内容为止。 If this is what you are trying to do then you can do it like this:
如果这是你想要做的,那么你可以这样做:
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var theInput = $('input#size').val();
if (!theInput.length) // Checking to see if there's something in the input
alert("Error");
else {
$.post("test.php", function (data, status) {
alert(data + ":" + status);
});
}
});
});
NOTE: It's important to note that in order for your PHP to run at all, you need to set up a local server (This might be why you are getting PHP errors).
注意:重要的是要注意,为了让您的 PHP 完全运行,您需要设置一个本地服务器(这可能是您收到 PHP 错误的原因)。 You can do that by either installing XAMPP or you can follow these instructions .
您可以通过安装XAMPP或按照这些说明进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.