jQuery Ajax简单调用

Ale*_*dro 19 jquery

我正在尝试一个基本的ajax调用.所以我托管在测试服务器上以下测试PHP: http://voicebunny.comeze.com/index.php?numberOfWords=10 这个网页是我自己的测试已经整合到VoiceBunny API 的http:// voicebunny.com/developers.

现在我需要使用jQuery在其他网页上获取该网页打印的数据.正如您所看到的,网页echo是一些JSON.如何从其他网页获取此JSON?

这是我的代码:

 $.ajax({

        'url' : 'http://voicebunny.comeze.com/index.php',
        'type' : 'GET',
        'data' : {
            'numberOfWords' : 10
        },
        'success' : function(data) {              
            alert('Data: '+data);
        },
        'error' : function(request,error)
        {
            alert("Request: "+JSON.stringify(request));
        }
    });
Run Code Online (Sandbox Code Playgroud)

我尝试了很多其他的变化,但我总是得到一个错误,而不是JSON.谢谢

小智 41

请在你的ajax调用中设置dataType配置属性,再试一次吧!

另一点是你使用ajax调用设置配置属性作为字符串,它作为参考站点是错误的

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});
Run Code Online (Sandbox Code Playgroud)

希望对你有所帮助!


Adr*_*asu 17

您还可以使ajax调用更通用,可重用,因此您可以从不同的CRUD(创建,读取,更新,删除)任务中调用它,并从这些调用中处理成功案例.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });
Run Code Online (Sandbox Code Playgroud)

  • 你的意思是清洁 (10认同)
  • 如果我们建议英语改进以及AJAX,OP意味着回声.没有丢失的信件或所有权,意味着没有撇号.如果我努力工作,我可以把这样的迂腐重新带回主题.我怀疑管理员会这么看. (2认同)
  • 或者,"更干净." 我建议走高路,更好地纠正.不要"tawulk layaik thayusse"并且无法处理干净的修正.以人类语法和最佳实践的名义.提及它没有害处.哦,thx,Umair代码! (2认同)