2012-12-27 111 views
0

我想获得URL变量(pid)到ajax请求(url)并没有取得任何成功。URL变量到ajax请求

我的网址是:www.domain.com/news.html?pid=1256

我的Java脚本:

$(document).ready(function() { 
var output = $('#news'); 
var id = jQuery(this).attr('pid'); 

$.ajax({ 
    url: 'http://www.domain.com/?post_type=news&post_id=' + id, 
    async: false, 
    callback: 'callback', 
    crossDomain: true, 
    contentType: 'application/json; charset=utf-8', 
    type: 'POST', 
    dataType: 'jsonp', 
    timeout: 5000, 
    success: function(data, status) { 
     $.each(data.posts, function(i, item) { 
      var news = '<div>' + item.title + '</div><div>' + item.content + '</div><hr/>'; 

      output.append(news); 


     }); 
    }, 
    error: function() { 
     output.text('There was an error loading the data.'); 
    } 
});}) 

非常感谢您的帮助。

+0

什么是'VAR ID = jQuery的(本).attr( 'PID');'应该在'$上下文做(文件).ready'回调? –

+0

你试图获得'pid'属性的元素是什么?你用'this'来定义它,它意味着你选择你的整个html文档,因为你得到'document'对象 –

+0

伙计我需要从url获得1256并将它插入到“$ .ajax({url:”,所以它会像 url:'http://www.domain.com/?post_type=news&post_id=1256, – qqruza

回答

2

如果我理解正确,您想从当前页面获取查询参数'pid'?

您可以通过window.location.search得到查询参数。

要获得一个特定的参数,您应该创建一个getQueryVariable()函数。

所以你的情况:

var getQueryVariable = function(variable) { 
    ... 
}; 
$(document).ready(function() { 
    var output = $('#news');  
    var id = getQueryVariable('pid'); 
    ... 
+0

嗨,真抱歉,我不是java中的大师,请你在这里给我写一行 – qqruza

+0

Eh?它是javascript ...你检查了链接吗?只需将该功能复制粘贴到你的代码中,并用上面的代码替换你的'var id'行即可。 – asgoth

+0

我已经得到了一个错误现在:未捕获ReferenceError:getQueryVariable没有定义 – qqruza