2-6

今天Leo童鞋帮我把代码发布到了测试环境。然后Test Buddy帮我verify之后终于check in了。到现在都不知道为啥我不能deploy……现在正在焦急的等待check-in result。谢谢大家的帮忙哇。

今天回头沿着《head first ajax》这本书搞了一下Ajax,觉得略坑。把自己踩过的坑写一下吧。这个Target是点击一个小图片,在一个DIV里面加载大图,同时更新文字信息。

首先我按照下载了基础代码(CSS、HTML)然后自己按照书上的流程写了JS,然后发现图片可以加载,但是文字怎么都不能加载。我就打开了Chrome的调试工具,发现我的JS里面好多bug,就开始一点点的改。然后发现貌似我压根没有服务器的代码……然后看了一眼书上提供的是个.php得。我顿时觉得囧了。实在不想配置php的环境,于是我在邓博文的指导下,参照着这篇博客写了一个web service。其实就是监听一个端口,然后根据端口的内容给出不同的结果,代码如下:

 1 namespace HttpServer
 2 {
 3     using System;
 4     using System.Collections.Generic;
 5     using System.IO;
 6     using System.Linq;
 7     using System.Net;
 8     using System.Text;
 9     using System.Threading.Tasks;
10 
11     class Program
12     {
13         HttpListener httpListener = new HttpListener();
14 
15         static void Main(string[] args)
16         {
17             Program program = new Program();
18 
19             program.Start();
20         }
21 
22         public void Start()
23         {
24             this.httpListener.Prefixes.Add("http://*:1234/");
25             this.httpListener.Start();
26 
27             Console.WriteLine("Listening, hit enter to stop");
28 
29             this.httpListener.BeginGetContext(new AsyncCallback(GetContextCallback),null);
30             Console.ReadLine();
31 
32             this.httpListener.Stop();
33         }
34 
35         public void GetContextCallback(IAsyncResult result)
36         {
37             HttpListenerContext context = this.httpListener.EndGetContext(result);
38             HttpListenerRequest request = context.Request;
39             HttpListenerResponse response = context.Response;
40 
41             StringBuilder stringBuilder = new StringBuilder();
42 
43             foreach (string key in request.QueryString.Keys)
44             {
45                 stringBuilder.Append(this.GetDescriptionByName(request.QueryString[key]));
46             }
47 
48             byte[] buffer = Encoding.UTF8.GetBytes(stringBuilder.ToString());
49 
50             response.ContentLength64 = buffer.Length;
51 
52             using (Stream outputStream = response.OutputStream)
53             {
54                 outputStream.Write(buffer, 0, buffer.Length);
55             }
56 
57             this.httpListener.BeginGetContext(new AsyncCallback(GetContextCallback), null);
58         }
59 
60         private string GetDescriptionByName(string name)
61         {
62             string description = string.Empty;
63 
64             switch (name)
65             {
66                 case "itemGuitar" : 
67                     description = "<p>Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.</p>";
68                     break;
69                 case "itemShades" :    
70                     description = "<p>Yoko Ono's sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.</p>";
71                     break;
72                 case "itemCowbell" :
73                     description = "<p>Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.</p>";
74                     break;
75                 case "itemHat" :
76                     description = "<p>Michael Jackson's hat, as worn in the \"Billie Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.</p>";
77                     break;
78                 default :
79                     description = "We dont have this item";
80                     break;
81             }
82 
83             return description;
84         }
85     }
86 }

然后在Chrome里面调试的时候,发现报错了:

XMLHttpRequest cannot load http://127.0.0.1:1234/itemName?itemCowbell. Origin http://127.0.0.1 is not allowed by Access-Control-Allow-Origin. 

这个是常见的跨域访问错误,有兴趣的同学可以看看:http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin。然后我在Han童鞋的指导下,把网站deploy到了IIS上,然后设置了XMLHttpRequest的表单头。然后发现在IE10下,这个东西可以跑了。但是Chrome之下仍然有限制。

但是发现仍然不会加载文字信息,于是我继续,调试,发现了一个蛋疼的问题,就是在设置innerHTML的时候,HTML大小写敏感……最后附上我的JS的代码:

window.onload = initPage;

function initPage()
{
    //find the thumbnails on the page
    thumbs = document.getElementById("thumbnailPane").getElementsByTagName("img");
    
    //set the handler for each image
    for (var i = 0; i < thumbs.length; i++)
    {
        image = thumbs[i];
        
        //carete the onclick function
        image.onclick = function()
        {
            //find the full-size image name            
            detailURL = 'images/'+ this.title + '-detail.jpg';
            document.getElementById("itemDetail").src = detailURL;
            getDetails(this.title);
        }
    }
}

function createRequest()
{
    if (typeof XMLHttpRequest != "undefined")
    {
        return new XMLHttpRequest();
    }
    else
    {
        alert("error");
    }
}

function getDetails(itemName)
{
    request = createRequest();
    
    if (request === null)
    {
        alert("Unalbe to create request");
        return;
    }
        
    var url = "http://127.0.0.1:1234/itemName?" + escape(itemName);
    
    request.open("GET", url, true);
    
    request.setRequestHeader("Access-Control-Allow-Origin","*");
    
    request.onreadystatechange = displayDetails;
    request.send(null);
}

function displayDetails()
{
    if (request.readyState === 4)
    {
        if (request.status === 200)
        {
            detailDiv = document.getElementById("description");
            detailDiv.innerHTML = request.responseText;
        }
    }
    
    
}

但是这个仍然不是问题的完美解决方案,完美方案估计今天来不及弄了。明天接着弄吧。理想中的情况是把服务端的代码和网站Deploy到一块,彻底避免跨域问题。当然还有一些其他的方法,比如使用JSONP之类的,回头看一下吧。

Good good study, day day up

posted on 2013-04-27 23:49  hibix  阅读(811)  评论(0编辑  收藏  举报

导航