简体   繁体   中英

xmlhttp request in javascript file causing errors

I have a javascript file which has some code somewhat like this:

var Slide =     
{   

    init: function()
    {
        var thumbs = new Array();
        thumbs = Core.getElementsByClass("thumb-img");
        var i;
        for (i=0; i<thumbs.length; i++)
        {
            Core.addEventListener(thumbs[i], "click",  (function( j){return function(){Slide.showImage(j);/*alert(j);*/};})(i));

        }
    },

Now, I am trying to pass xmlhttp objects in this javascript file. I am adding the following just above the init: function() ...

var xmlhttp;

function getVote(int)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
var value = int;
alert(value);
var url="user_submit.php";
url=url+"?vote="+int;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
  if (xmlhttp.readyState==4)
  {
  document.getElementById("captionbox").innerHTML=xmlhttp.responseText;
  }
}

function GetXmlHttpObject()
{
var objXMLHttp=null;
if (window.XMLHttpRequest)
  {
  objXMLHttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
return objXMLHttp;
}

...but firebug gives me error: missing : after property id var xmlhttp;\\n

What am I doing wrong?

That's invalid syntax - you can't have code just floating around in an object. The easiest way to do that would be to just move that code outside the Object.

A better way would be to have a function initXhr() , which is called by init() . That would contain the same code as you tried to put before init . Then, add at the end:

this.xmlHttp = xmlHttp;

Then, in other functions, use this.xmlHttp .

It looks like you're putting normal Javascript inside an object block.

Move the XMLHTTP code block above the line var Slide = .

If this doesn't help, please show us the entire file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM