开发者

How do I add a php variable to this jquery url setting?

I'm trying to make the URL in the following example contain a php variable like this:

http://api.crunchbase.com/v/1/company/$company.js

This is my jquery code:

$.ajax({
url: "http://api.crunchbase.com/v/1/company/airbnb.js",
dataType: 'jsonp',
s开发者_如何学Pythonuccess: function(results){
    var number_of_employees = results.number_of_employees;
        }

What do I need to do to achieve this?

Thanks!


You'll need to output the variable as JavaScript from PHP at some point in the script. This can be done quite easily using json_encode:

var company = <?php echo json_encode($company) ?>;

Note that this will have to be placed in a file that is actually executed by PHP, rather than an inert .js file. One way to achieve this is to put it in an inline <script> in the HTML in your PHP template; e.g.

<script type="text/javascript">
    var company = <?php echo json_encode($company) ?>;
</script>


Try this:

<script type="text/javascript">
    var company = <?php echo json_encode($company); ?>;
    alert(company);
</script>

You're setting the company variable with the output of $company, you can then use this variable however you please in JavaScript.

$.ajax({
url: "http://api.crunchbase.com/v/1/company/" + company + ".js",
dataType: 'jsonp',
success: function(results){
    var number_of_employees = results.number_of_employees;
}


Can you try this, assuming you have the company name in the php $company variable:

$.ajax({
url: "http://api.crunchbase.com/v/1/company/<?php echo $company ?>.js",
dataType: 'jsonp',
success: function(results){
    var number_of_employees = results.number_of_employees;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜