Ho un modulo in cui un utente può digitare un nome utente e verrà visualizzato l'ID corrispondente ad esso. Sto usando AJAX per inviare i dati e visualizzare il risultato (l'ID) senza aggiornare la pagina.
Non ricevo errori nella console, ma nessun ID viene visualizzato dopo l'invio del modulo.
HTML:
<form method="post" id="form">
<input type="text" id="username">
<input type="submit">
<form>
<div id="resulthere"></div> <!-- where the ID is supposed to be displayed -->
AJAX / JQuery:
<script>
$(document).ready(function(){
$("form#form").submit(function(event) {
event.preventDefault();
var username = $("#username").val();
$.ajax({
type: "POST",
url: "result.php",
data: "username=" + username,
success: $("#resulthere").html(event)
});
});
});
</script>
PHP (results.php):
<?php
if(!empty($_POST["username"])) { // checks to make sure the username isn"t empty
$json = file_get_contents("http://example.com?username=".$_POST["username"]);
$json2 = json_decode($json);
$id = $json2->ID; // gets the ID
echo $id; // displays the ID
}
?>
risposte:
1 per risposta № 1Questa riga del tuo input
<input type="text" id="username">
sarebbe meglio se avesse un nome, L'attributo name viene utilizzato per fare riferimento a elementi in un JavaScript o per fare riferimento ai dati del modulo dopo l'invio di un modulo.
<input type="text" name="username" id="username">
e farlo nel tuo jquery
$(document).ready(function(){
$("form#form").submit(function(event) {
event.preventDefault();
var username = $("#username").val();
$.ajax({
type: "POST",
url: "result.php",
data: { "username": username },
success: function (result) {
$("#resulthere").html(result)
}
});
});
});
Nel codice di Ajax hai,
data: "username=" + username
che viola la sintassi jquery, quello che hai fatto è concatenare le due stringhe, "nome utente" e valore dall'input # nome utente.
data : {
"username":username
},
"username"
, è un nome di input while username
è il valore di quell'input
mentre questo, success: $("#resulthere").html(event)
anche violare la sintassi,
per ulteriori letture, è possibile fare riferimento a questa documentazione http://api.jquery.com/jquery.ajax/
0 per risposta № 2
Basta cambiare
data: "username=" + username,
a
data: { "username" : username },