LeRoy
LeRoy

Reputation: 3215

Using a web service for cross site scripting

I want to pull down a feed (like twitter) and place in on a page using javascript (jquery). Ultimately, the "service" just needs to hand off JSON. I created a web service that allows me to do that, sort of. I don't know if using a stream reader is all that efficient and I was a little bothered by having to use what amounts to 2 evals on the clientside.

My question is twofold: is there a better method than using a web service and two, is there a problem with my implementation?

.asmx:

[WebMethod]
public string HelloWorld()
{
    WebRequest request = WebRequest.Create("http://twitter.com/statuses/user_timeline/username.json?count=1");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string tmp = reader.ReadToEnd();
    response.Close();
    reader.Close();
    return tmp;
}

.aspx

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script>
    $(document).ready(function() {
        $.ajax({
            url: "WebService1.asmx/twitter",
            type: "POST",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(obj) {
                var t = eval(obj.d)[0].text;
                $('div').html(t);
            }
        })
    });
</script>

Upvotes: 0

Views: 1633

Answers (2)

awright18
awright18

Reputation: 2333

2 part answer to your question. 1st of all use

System.Net.WebClient client = new System.Net.WebClient();
string twitterFeed = client.DownloadString("http://twitter.com/statuses/user_timeline/username.json?count=1") 

This will return the string without all the excess lines of code.

2nd the twitter api is a webservice that returns json. So you don't need to recreate the wheel. Here is a nice article and a jquery-twitter library that will allow you to easily get your timeline, like this.

$.twitter.user_timeline('username', function(resp) {
      $('body').append('  
        '+this.user.name+': '+this.text+'
        ');  
});

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28844

Your server side code isn't really doing anything, Why aren't you just calling the twitter api directly from the client?

Upvotes: 0

Related Questions