Use IBM watson API with jquery's $.ajax

2019-07-04 09:46发布

I'm looking at the documentation for the watson API ( http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/qaapi/#apiRef ) but there isn't a clear way regarding how to use the API with client-side js. I'd like to use jquery's $.AJAX function.

How do I authenticate my account with the API using jquery and the send it a question? Once I get the json form the API, I can parse that, but how do I send it?

Here is how I'd think about doing this, but I don't know where I get the authentication information from BlueMix and then to where I send the request to get the JSON.

var questionJSON = {
    'question': {
        'evidenceRequest': {
            'items' : 1
        },
        'questionText': question
     }
};
$.ajax({    
    url: '' // url,
    dataType: 'json',
    method: 'PUT',
    beforeSend: function(xhr){
        //xhr.setRequestHeader('Authorization', 'Basic '+btoa(accessToken+':'));
    },
    success: function(answerJSON){
        // parse answerJSON
    }
});

3条回答
别忘想泡老子
2楼-- · 2019-07-04 10:25

I believe you may need to use similar logic like below:

function addUser(event)
{
.......................
$.ajax({    
url: '/users/adduser',,
dataType: 'json',
method: 'PUT',
beforeSend: function(xhr){
    //xhr.setRequestHeader('Authorization', 'Basic '+btoa(accessToken+':'));
},
success: function(answerJSON){
    // parse answerJSON
}
});
 };

/* * POST to adduser. */

router.post('/adduser', function(req, res) {
var db = req.db;


 db.collection('userlist').insert(req.body, function(err, result){
    res.send(
        (err === null) ? { msg: '' } : { msg: err }
    );
    });
});

you can follow below link for more info on client side js:

http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

查看更多
冷血范
3楼-- · 2019-07-04 10:35

You are trying to do a Cross-domain requests (http://en.wikipedia.org/wiki/Same-origin_policy). That is not possible.

The only way to call the qa service from the client side its by using jsonp (http://en.wikipedia.org/wiki/JSONP). but that is not supported now. I will suggest you to create an app in Bluemix and use it as proxy between your code and the service.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-04 10:46

Please take a look at my tutorial on IBM developerWorks on using Watson's Question and Answer service - http://www.ibm.com/developerworks/cloud/library/cl-watson-qaapi-app/index.html#N10229

Regards Ganesh

查看更多
登录 后发表回答