我正在尝试获取 javascript 函数的结果以发送到 PHP 文件。因此我可以将其用作 PHP 变量。
这是我想在 PHP 文件中使用的函数:
function password()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
这是一个原型(prototype)(所以我不担心安全风险)
谢谢。
更新:有人可以告诉我如何将其作为表单提交吗?
最佳答案
您可以使用 AJAX 在 php 中发送您的值! :)
function password(){
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.yourSite.com/ajax.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === 4 && && xhr.status === 200) {
console.log(xhr.responseText);
}
}, false);
xhr.send('text=' + password());
Post通过表单发送数据,所以,我们应该添加一个content-type
:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
然后在你的 php 代码中:只需这样做:
<?php echo $_POST['text']; ?>
关于javascript - 将 javascript 函数的结果发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161302/