Pregunta

I am attempting to call a Mockjax 'post' endpoint through jQuery $.post method as below

service.js

$.mockjax({
    url: '/api/callfor/data',
    type: 'post',
    responseTime: 1000,
    contentType: 'text/json',
    dataType: 'json',
    responseText: {
        success: true,
        data: 'Hello World'
    }
});

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Mock Ajax call</title>
</head>
<body>
    <script src="jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="jquery.mockjax.js" type="text/javascript"></script>
    <script src="service.js" type="text/javascript"></script>
    <script type="text/javascript">

        $.post('/api/callfor/data', {}, function (resp) {
            var html = (resp.success) ? 'Your data is ' + resp.data : 'No data received';
        });
    </script>
</body>
</html>

However on calling the method, the resp always coming as undefined. What could be wrong here?

¿Fue útil?

Solución

The type of data being requested or rather say that the type of data endpoint provides i.e. JSON was not mentioned in the call.

So changing the post call to

 $.post('/api/callfor/data', {}, function (resp) {
            var html = (resp.success) ? 'Your data is ' + resp.data : 'No data received';
        }, 'json');

This returns the data.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top