2012-03-23 101 views
1

我是新来的ajax,并试图让下面的脚本工作。我只想从json对象获取信息并将其打印到文档中。简单的ajax请求

这里是JSON文件名为companyinfo.json:

{ 
'id':1, 
'name':'Stack' 


} 

Ajax请求如下:

ar xhr = false; 
var xPos, yPos; 

$(function(){ 

    var submitButton = $("#dostuff"); 
    submitButton.onclick = sendInfoRequest; 

}); 

function sendInfoRequest (evt) { 
    if (evt) { 
     var company1 = $("#companyInput1").val; 
     var company2 = $("#companyInput2").val; 
    } 
    else { 
     evt = window.event; 
     var company = evt.srcElement; 
    } 
    $.ajax({ 
     url : 'companyinfo.json', 
     dataType: 'json', 
     data: company1, 
     success: function(data) { 
      console.log(data); 
      var items = new Array(); 
      $.each(data, function(key, val) { 
       items.push('<li id="' + key + '">' + val + '</li>'); 
      }); 
     } 

    }); 


    return false; 
} 
console.log(data.id); 

从简单开始。我只是console.log data.id来查看脚本是否从json文件返回了一个值。

将其写入到文件,我会做这样的事情,调用showContents功能在上面的回调函数:

function showContents(companyNumber) { 
    if (xhr.readyState == 4) { 
     if (xhr.status == 200) { 
      var outMsg = xhr.responseXML; 
      $("." + data.companyName.toLowerCase + companyNumber).innerHTML(data.companyName) 
     } 
     else { 
      var outMsg = "There was a problem with the request " + xhr.status; 
     } 


    } 
} 

我是很新,阿贾克斯,但希望这有一定的道理。由于

+1

所以......问题是什么? – hugomg 2012-03-23 03:09:23

+0

我应该如何设置company1的值(也就是我应该在我提交的输入字段中输入什么内容)。以及如何格式化相应的json文档以反映公司名称?当我提交上面的脚本时,什么都没有发生 – 2012-03-23 03:30:57

回答

0

,如果你想获得的东西,我认为你应该在你的$就应该是这样的添加

type:"GET" 

$.ajax({ 
    url : 'companyinfo.json', 
    dataType: 'json', 
    type:"GET", 
    contentType: "application/json; charset=utf-8", 
    data: company1, //What is your purpose for adding this? 
    success: function(data) { 
     console.log(data); 
     var items = new Array(); 
     $.each(data, function(key, val) { 
      items.push('<li id="' + key + '">' + val + '</li>'); 
     }); 
    } 

}); 
0

林不知道这个在你的代码:

var company1 = $("#companyInput1").val; //should it be with()?? 
var company2 = $("#companyInput2").val; //should it be with()?? 

应与()像这样的:

var company1 = $("#companyInput1").val(); 
var company2 = $("#companyInput2").val(); 
0

最简单的方法来获取和分析JSON是使用$.getJSON

// you need to use a map as your data => {key : value} 
$.getJSON("companyinfo.json", {company : company1}, function(data){ 
    console.log(data); 
    var items = []; // new Array(); 
    $.each(data, function(key, val){ 
    items.push('<li id="' + key + '">' + val + '</li>'); 
    }); 
    // do something with items 
}); 
0

你可以这样做:

$.getJSON("getJson.ashx", { Index: 1 }, function (d) { 
        alert(d); 
       });