There is an existing way to use SageMathCell as a web API. It's described briefly here, but since the documentation needs improvement I'll record some information here.
One way to access the API is by submitting a form to http://sagecell.sagemath.org/service (do not include a trailing slash on this URL). The documentation has a JSFiddle that I have updated for your specific example. Your command (or any other that returns a printable result) appears in a text input on the fiddle, and the output is printed below when the button is clicked.
The fiddle works by URL encoding the command and posting it to the server. If you don't want to use a form, you can read the input from a text field and submit it to the server with an XMLHttpRequest. Here's some sample code that sends your URL-encoded command to the server and opens an alert window with the result:
var xhr = new XMLHttpRequest();
xhr.open( 'POST', 'http://sagecell.sagemath.org/service', true );
xhr.onload = function() {
var data = JSON.parse( xhr.responseText );
alert( data.stdout );
}
xhr.setRequestHeader( 'content-type', 'application/x-www-form-urlencoded' );
xhr.send( 'code=P%3DPrimes()%3B+print+P.next(2016)' );
And for command line people, here's how to get the same JSON data using cURL:
curl -d 'code=P%3DPrimes()%3B+print+P.next(2016)' http://sagecell.sagemath.org/service
References for SageMath as a web API came from this issue on GitHub. Thanks @novoselt!