javascript 使用 php 更改 html 元素的内部文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7547908/
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
use php to change a html elements inner text
提问by Graeme Leighfield
I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
我有一个基本表单,我需要对其进行一些验证,我有一个跨度区域,我想按下提交按钮,如果字段为空,则在该框中显示预定义的消息。
Something like
就像是
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
我知道我可以用 jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here") 做到这一点,但是我怎样才能用 PHP 做到这一点?
Bit of a new thing for me with php, any help greatly appreciated :)
php 对我来说是一个新东西,非常感谢任何帮助:)
Thanks
谢谢
回答by Erik Terwan
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
你可以通过几种方式做到这一点。您可以创建一个 $error 变量。使它始终创建 $error (即使一切都检查正常)但如果没有错误,它需要为空,否则该值必须是错误。
Do it like this:
像这样做:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
回答by Nick Nizovtsev
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
在 $_REQUEST、$_GET 或 $_POST 变量中发送到 php 的表单字段...
For validate the field param you may write like this:
为了验证字段参数,您可以这样写:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
回答by masoud
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
如果你想在客户端动态改变它,除了ajax别无他法。PHP 在服务器端工作,您必须使用 post/get 请求。
回答by Rijk
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
你不能用 PHP 在客户端做任何事情。你需要Javascript。如果你真的需要 PHP(比如检查数据库什么的),你可以使用 Javascript 进行 Ajax 调用,并将返回值放在页面上的 div 中。