如何在json url中插入变量?

时间:2016-11-13 14:41:34

标签: javascript jquery json

我正在尝试在json url中使用我定义的var:

var articleName = "test";

$.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q='+articleName+'&searchType=image&fileType=jpg&imgSize=xlarge&alt=json`",

我试过:q='+articleName+'但是错了

4 个答案:

答案 0 :(得分:2)

怎么样?
var params = {
 key1: val1,
 key2: val2
};

$.getJSON( "https://www.googleapis.com/customsearch/v1", params, function(res) {

});

答案 1 :(得分:1)

"之前和之后使用+,例如&q='"+articleName+"'&

另一种解决方案是使用data

选项1:仅用于文章名称

$.getJSON("https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&searchType=image&fileType=jpg&imgSize=xlarge&alt=json",{
    "q":articleName
},

选项2:所有参数

$.getJSON("https://www.googleapis.com/customsearch/v1",{
    "q"          : articleName,
    "alt"        : "json",
    "imgSize"    : "xlarge",
    "fileType"   : "jpg",
    "searchType" : "image",
    "cx"         : "CX_MY",
    "key"        : "API_MY"
},

答案 2 :(得分:0)

尝试:

"some " + yourVar + " text"

'some ' + yourVar + ' text'

或使用模板文字(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

答案 3 :(得分:0)

$.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q="+articleName+"&searchType=image&fileType=jpg&imgSize=xlarge&alt=json"`