这个问题在这里已有答案:
视图
<input type="text" id="textToDisplay" />
<br />
<input type="button" value="Add message" onClick="showMessage()" />
<br />
<span id="messageSpan"><span>
JS
function showMessage() {
var message = jQuery("#textToDisplay").val();
jQuery("#messageSpan").text(message);
}
顺便说一句,我正在使用laravel。基本上,我想要做的是,如果用户输入22,那么它将显示成功消息。所有这些都在PHP中进行,而无需更改/添加js。 jsfiddle example
基本上我的想法是这样的,
<?php
if(<span id="messageSpan"><span> == 22)
success
else
<span id="messageSpan"><span>
?>
你不能像上面描述它那样做。您要么只使用javascript / jquery,要么使用这两种语言(php和javascript)并向服务器发送ajax请求并在其中执行某些操作并将一些数据返回给客户端(javascript)并在您的视图中显示。
我添加了一些评论,以便更好地理解这个过程,如果您有任何问题请问。
我会使用ajax这样做,所以你将使用javascript和php,这对你来说应该更好。
所以这是你的HTML标记:
<input type="text" id="textToDisplay" />
<br />
<input type="button" value="Add message" onClick="showMessage()" />
<br />
<span id="messageSpan"><span>
现在,您将使用ajax将输入值发送到控制器,如下所示:
$(document).ready(function(){
// on each key up we are going to sent the value later you should probably change this and sent the value after you click on a button
$('#sentMessage').keyup(function(){
// this holds the current value of the input field
var inputValue = $(this).val();
// you are going to sent the input data to this route '/showMessage'
// you are going to use the post method
$.ajax({
type: "POST",
url: '/showMessage',
data: {
inputValue: inputValue
},
// if you post is successful then do following ....
success: function(data) {
// here we are just going to show the message inside you span, the returned data comes from your controller
$("#messageSpan").text(data.inputValue);
},
// if there was an error do following ....
error: function(data) {
// if there was an error you could just show a message with some error message
$("#messageSpan").text('ERROR!');
}
});
});
});
在Laravel Controller类中,您需要具有如下函数:
public function showMessage(Request $request)
{
// $inputValue contains the inputValue data from your ajax call
$inputValue = $request->inputValue;
// You could / should also do some validation here later on ...
// Thus you should probably save the data, I do not know what excatly you are going to do with it later ...
// now we are sending back the data
return response()->json($inputValue);
});
你还需要做些什么来创建一个合适的路由,以便你的ajax请求找到它。所以在你的routes.php中你需要创建一个这样的路由:
Route::get('/showMessage', ['as' => 'showMessage', 'uses' => 'YourController@showMessage']);