Passing Javascript String to PHP output
I'm using this web service that prints out table using Javascript functions. I need the table to print out in plain html. This could be done if the Javascript string was transferred to a PHP file. So basically, this is similar to AJAX, but it is in reverse开发者_开发百科.
You could do that with ajax also
var value = 'This is a test';
if ($(value).val() != 0) {
$.post("jquery2php.php", {
variable:value
}, function(data) {
if (data != "") {
alert('We sent Jquery string to PHP : ' + data);
}
});
}
Important thing here is we are using $.post, so we are can gather the information with $_POST
We are sending only 1 value, named variable.
PHP part;
<?php
$jqueryVariable = $_POST['variable'];
echo $jqueryVariable;
?>
I believe, this is the most elegant way to achieve what you want.
not necessarily reverse, You could pass the string as a URL variable (www.yoursite.com/?string=yourvariable) and have PHP process it from there.
I've quoted a ugly method down here But i dont recommend this..
Instead store values in hidden fields in forms and access them through js or do something else..
<?php
echo "<script type=text/javascript>var x = $value; </script>";
?>
then use the variable x in js..
Anyway if you explain ur situation a bit clearer, we can give u best alternate solution
what you should do is use jQuery's .load() to load in the php's html results into the page
in the docs i've linked above they give this example
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
</script>
EDIT
in response to your comment on Pixeler's post. You will not be able to just view the source of a ajax based solution. if your ultimate goal is to be able to read the source you have basically three options
- send them to a new page
- load in an iframe
- do it the way you have, use fire fox and web devloper addon which will allow you to view generated source. (or something similar)
I'm not sure why there is a need to see the source users don't really care about the source typically the developer uses that
精彩评论