问题
Possible Duplicate:
How to pass JS variable to php?
Passing javascript variables to php?
how to pass a valu from javascript function, I have this kind of code
function next(c,q){
var y=Number(q);
var x=Number(c)+1;
var texta=document.getElementById('myText');
var content=document.getElementById('woo'+x);
var page=document.getElementById('paged');
var thik=document.getElementById('lengthik');
texta.value=content.value;
page.value=x;
thik.value=y;
var z=100/y;
//update progress bar
$("#progressbar").progressbar("option", "value", $("#progressbar").progressbar("option", "value") + z);
if($("#progressbar").progressbar("option", "value") < 100){
$("#amount").text($("#progressbar").progressbar("option", "value")+"%");
}
else{
$("#amount").text(100+"%");
}
}
and I want to throw the new value of the id #progressbar into the php. this id is dynamic because it is a probressbar
回答1:
To communicate between javascript (which runs on the client machine's browser) and PHP (which runs on your server) you need to use ajax. Since you are already using jQuery, I suggest using their abstraction method $.ajax(). It would look something like this:
// post value of #progressbar id to my php page
$.ajax({
url: myPHPPage.php,
data: JSON.stringify({ progressbarID: '#progressbar' }),
success: function (dataFromServer) {
alert('it worked!');
},
error: function (jqXHR) {
alert('something went horribly wrong!');
}
});
回答2:
Try this:
$.ajax({
type: "GET",
url: "yourphpfile.php",
data: "texta=" + texta+ "&content=" + content// texta,contentare javascript variables
success: function(response){
if(response != '') {
//success do something
} else {
// error
}
}
});
回答3:
So you have two options. Javascript can only pass variables to PHP through ajax. This is because javascript runs on the client browser and PHP runs on the server.
Option 1 - use Ajax. Javascript:
//update progress bar
$.ajax({
type: "POST",
url: "some.php",
data: { num: y } //or use q instead of y. its what you passed in
}).done(function(data) {
$('#amount').text(data);
});
this is the php file
<?php
//some.php
$complete = $_POST['num'];
$progress = $complete / $total; //you'll have to set what "total" is.
$progress .= '%';
echo $progress;
?>
Option 2 - use PHP when the page loads and then use javascript to update the progress bar. This is like using PHP and Javascript together, but technically you are using PHP to generate javascript code.
function next(c,q){
var y=Number(q);
var x=Number(c)+1;
var complete = (c / <?php echo $total;?>);
//update progress bar
//not sure how your progress bar library works.
//but maybe like this:
$("#progressbar").progressbar({"value" : complete});
}
来源:https://stackoverflow.com/questions/14139955/how-to-pass-a-value-from-javascript-function