read a json response in a html/js file
Is the below possible.
I am getting a ajax response below:
HTML
<body>
<input type="text"></input>
<div id="trydiv"></div>
</body>
JS
$.ajax({
type: "POST",
url: "json.php",
data: 'val='+$('input').val(),
success: function开发者_如何学Python(response){
$('#trydiv').load("try1.js");
}
});
json.php
<?php
echo json_encode($_POST['val']);
?>
try1.js
<script type="text/javascript">
$(function(){
alert(response);
});
</script>
Since in the success function, 'm passing response, should "response" not be available for try1.js. Is there anyway we can pass response to a js/html file and use in that?
No, response
will not be available, unless you assign response
to a global variable (and assuming browser security lets you load such scripts dynamically). I think it would be helpful though if you clarify more about what you are trying to achieve and why.
Also, maybe you just did it for formatting, but a file try1.js should not have script tags inside of it.
today i came across an very interesting script that showed me how to take parameters from the script tag:
$.ajax({
....
success: function(response){
$('#trydiv').load("try1.js");
var scr = document.createElement('script');
scr.type = 'load.js?'+escape(response);
document.getElementsByTagName('head')[0].appendChild(scr);
}
});
Now inside your load.js:
// get the parameters from the script tag
var scripts = document.getElementsByTagName('script');
var data ='';
for (var i=0,l= scripts.length;i<l;i++){
if (scripts[i].src.indexOf('load.js') != -1){
data = scripts[i].src.slice(scripts[i].src.indexOf('?')+1);
}
}
// now you can do alert the data
alert(data);
This might seem complicated but study it a little and you will see i can help you with your particular problem
精彩评论