javascript JS 提示 PHP 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26209967/
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
JS Prompt to PHP Variable
提问by Ken
Is this possible? Or do I really need to AJAX JS first?
这可能吗?还是我真的需要先使用 AJAX JS?
<?php
echo'< script type="text/javascript">var eadd=prompt("Please enter your email address");< /script>';
$eadd = $_POST['eadd']; ?>
and how can I do that with AJAX?
我怎样才能用 AJAX 做到这一点?
回答by divakar
Its not possible. You should use ajax. jQuerywas used in the following example:
这是不可能的。你应该使用ajax。以下示例中使用了jQuery:
<script>
var eadd=prompt("Please enter your email address");
$.ajax(
{
type: "POST",
url: "/sample.php",
data: eadd,
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
</script>
in php file
在 php 文件中
<?php
echo $_POST['data'];
?>
回答by meda
Ajax (using jQuery)
Ajax(使用jQuery)
<script type="text/javascript">
$(document).ready(function(){
var email_value = prompt('Please enter your email address');
if(email_value !== null){
//post the field with ajax
$.ajax({
url: 'email.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
//do anything with the response
console.log(response);
}
});
}
});
</script>
PHP
PHP
echo 'response = '.$_POST['data'];
Output:(console)
输出:(控制台)
response = [email protected]
回复 = [email protected]
回答by rogelio
Is not possible directly. Because PHP is executed first on the server side and then the javascript is loaded in the client side (generally a browser)
直接是不可能的。因为PHP先在服务端执行,然后在客户端(一般是浏览器)加载javascript
However there are some options with or without ajax. See the next.
但是,有一些选项可以带或不带 ajax。见下。
With ajax. There are a lot of variations, but basically you can do this:
与 ajax。有很多变化,但基本上你可以这样做:
//using jquery or zepto
var foo = prompt('something');
$.ajax({
type: 'GET', //or POST
url: 'the_php_script.php?foo=' + foo
success: function(response){
console.log(response);
}
});
and the php file
和 php 文件
<?php
echo ($_GET['foo']? $_GET['foo'] : 'none');
?>
Witout ajax:If you want to pass a value from javascript to PHP withoutajax, an example would be this (although there may be another way to do):
没有 ajax:如果你想在没有ajax 的情况下将一个值从 javascript 传递到 PHP ,一个例子是这样的(尽管可能有另一种方法):
//javascript, using jquery or zepto
var foo = prompt('something');
//save the foo value in a input form
$('form#the-form input[name=foo]').val(foo);
the html code:
html代码:
<!-- send the value from a html form-->
<form id="the-form">
<input type="text" name="foo" />
<input type="submit"/>
</form>
and the php:
和 php:
<?php
//print the foo value
echo ($_POST['foo'] ? $_POST['foo'] : 'none');
?>