使用jQuery访问Restful Web服务时,用户名和密码不正确

时间:2012-02-16 04:01:36

标签: jquery html

我有这段代码。

var txt =“username = admin& password = admin”;

    var jsonText = JSON.stringify({username:'test', password:'test'});
    $.ajax( {
        url : 'http://localhost/testService/loadpayments/',
        type: "GET",
        contentType: "application/json; charset=utf-8",
        data:jsonText,
        dataType: "json",
        processdata:false,
        error : function(result) {
            $('#items').html(result);
        },
        success : function(model) {
            $("#items").html(model);
        }
       });

现在,当我在firefox中运行它并在控制台上查看它时,它说错误的用户名和密码,但我正确提供了两者。当我尝试使用用户名和密码(两者都正确提供)粘贴网址时,它会运行并正常返回。我做得对吗?我对这种东西比较新。谢谢。

2 个答案:

答案 0 :(得分:2)

我可以从您的代码段中看出,您的RESTful服务希望您提供用户名和密码作为查询字符串参数。如果是这种情况,那么您的请求网址应如下所示:

http://localhost/testService/loadpayments/?username=test&password=test

但是,您的代码生成的请求URL是:

http://localhost/testService/loadpayments/?{%22username%22:%22test%22,%22password%22:%22test%22}

无需对参数进行字符串化。相反,将对象文字传递给AJAX调用的data参数,并将processData设置为true(或者根本不指定,因为它默认为true),以便将对象转换为查询字符串参数:

var credentials = {username: 'test', password: 'test'};
$.ajax({
    url : 'http://localhost/testService/loadpayments/',
    type: "GET",
    contentType: "application/json; charset=utf-8",
    data: credentials,
    dataType: "json",
    processData: true, // defaults to true
    error : function(result) {
        $('#items').html(result);
    },
    success : function(model) {
        $("#items").html(model);
    }
   });

答案 1 :(得分:0)

您正在使用

var jsonText = JSON.stringify({username:'test', password:'test'});

相反,如果使用stringify,则需要创建一个对象。在JavaScript中创建一个名为user的对象,如下所示:

var user = new Object();
user.username = "test";
user.password = "test";

var jsonText = JSON.stringify(user);

也许这个例子会更好地解释

var contact = new Object(); 
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];

var jsonText = JSON.stringify(contact);

/* The value of jsonText is:
'{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}'
*/

这是未经测试但应该有用。

修改

我坚持对象的想法,并同意RoccoC5,因为查询字符串中的参数是要走的路。