我在这段代码上遇到了一些麻烦。我将获取 4 个输入的值,使用 jQuery 将它们传递给 PHP API,使用我创建的 PHP API 文件计算密码,并将该密码作为 json_encoded 的数据参数返回。您将在下面找到代码:
PHPPasswordGenerator.php
<?php
header("Content-Type: application/json; charset: UTF-8;");
$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$special = array('!','?',"'",'"','£','$','%','&','/','(',')','=','@','#','§','[',']','{','}');
$minLetters = array();
$maxLetters = array();
$numbers = array();
$specialCharacters = array();
$final = '';
$min = $_REQUEST["typeA"];
$max = $_REQUEST["typeB"];
$num = $_REQUEST["typeC"];
$spec = $_REQUEST["typeD"];
if(isset($min) or isset($max) or isset($num) or isset($special)){
for($i = 0; $i < $min; $i++){
array_push($minLetters, $letters[rand(0,count($letters)-1)]);
}
for($i = 0; $i < $max; $i++){
array_push($maxLetters, strtoupper($letters[rand(0,count($letters)-1)]));
}
for($i = 0; $i < $num; $i++){
array_push($numbers, rand(0,9));
}
for($i = 0; $i < $spec; $i++){
array_push($specialCharacters, $special[rand(0,count($special)-1)]);
}
$final .= implode('',$minLetters) . implode('',$maxLetters) . implode('',$numbers) . implode('',$specialCharacters);
}
print(json_encode($final));
?>
jQuery 代码
$(document).ready(function(){
//Chiamata AJAX sui dati generati dal generatore di Password in PHP
$("#generator").on("click", function(){
//Mentre il focus è sull'input, modifica il valore val()
$.getJSON("passwordgenerator.php",
{
typeA : $("#typeA").val(),
typeB : $("#typeB").val(),
typeC : $("#typeC").val(),
typeD : $("#typeD").val()
},
function(data){
console.log("Success: " + data);
$("#generated").append("<h3></h3>").html(data);
}).fail(function(err){console.log(err)});
});
});
这是 body 的一部分
<form>
<label for="A">Lettere Minuscole</label><input type="text" name="typeA" id="typeA">
<label for="B">Lettere Maiuscole</label><input type="text" name="typeB" id="typeB">
<label for="C">Numeri</label><input type="text" name="typeC" id="typeC">
<label for="D">Caratteri Speciali</label><input type="text" name="typeD" id="typeD">
<button id="generator">Generate Password</button>
</form>
<div id="generated"></div>
现在,问题是:每当我在输入中放入一个数字并将其发送到 PHP 文件时,$final
变量都会进行 json_encoded 并发送回 javascript 文件。如果我执行类似 console.log(data)
的操作,我实际上会看到一个随机生成的密码,其中包含我想要的规范,但随后我尝试执行以下操作:
$("#generate").text(data);
但是数据并没有进入内部生成。我也尝试使用 html(data),但没有用。我执行了 console.log(typeof data);
来查看它确实是一个字符串,正如我想要的那样,而且它确实是一个字符串。
最佳答案
JSON.stringify(jsondata) 将 JSON 转换为字符串。如果要将数据字符串解析为 JSON,请使用 JSON.parse(string)。我不明白你的实际问题是什么
关于javascript - $.getJSON 使用数据参数修改 HTML 元素上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831913/